Stage Harbor release files 94001-94500
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tasks/tasksmith-ecb1931929df/tests/source/examples/conditional_generation/peft_lora_seq2seq_accelerate_fsdp.py +145 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/conditional_generation/peft_prefix_tuning_seq2seq.ipynb +426 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/conditional_generation/peft_prompt_tuning_seq2seq.ipynb +653 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/conditional_generation/peft_prompt_tuning_seq2seq_with_generate.ipynb +712 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/conditional_generation/requirements.txt +8 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/corda_finetuning/README.md +257 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/corda_finetuning/corda_finetuning.py +276 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/corda_finetuning/datautils.py +235 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/corda_finetuning/preprocess.py +165 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/cpt_finetuning/README.md +64 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/cpt_finetuning/cpt_train_and_inference.ipynb +1555 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/delora_finetuning/README.md +102 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/delora_finetuning/delora_finetuning.py +189 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/dna_language_models/dna_lm.ipynb +0 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/dora_finetuning/QDoRA_finetuning.ipynb +0 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/dora_finetuning/README.md +105 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/dora_finetuning/dora_finetuning.py +208 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/ephemeral_gpu_offloading/load_with_dora.py +103 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/eva_finetuning/README.md +159 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/eva_finetuning/eva_finetuning.py +96 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/eva_finetuning/eva_finetuning_multi_accelerator.py +132 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/eva_finetuning/utils.py +76 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/evaluation/lora-lm-eval.ipynb +0 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/feature_extraction/peft_lora_embedding_semantic_search.py +502 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/feature_extraction/peft_lora_embedding_semantic_similarity_inference.ipynb +0 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/feature_extraction/requirements.txt +10 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/fp4_finetuning/finetune_fp4_opt_bnb_peft.py +195 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/gralora_finetuning/README.md +73 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/gralora_finetuning/gralora_finetuning.py +189 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/hra_dreambooth/README.md +98 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/hra_dreambooth/a_purple_qwe_backpack.png +3 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/hra_dreambooth/dreambooth_inference.ipynb +0 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/hra_dreambooth/requirements.txt +12 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/hra_dreambooth/train_dreambooth.py +621 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/hra_dreambooth/train_dreambooth.sh +185 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/hra_dreambooth/utils/__init__.py +0 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/hra_dreambooth/utils/args_loader.py +377 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/hra_dreambooth/utils/dataset.py +128 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/hra_dreambooth/utils/tracemalloc.py +62 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/image_classification/README.md +15 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/image_classification/image_classification_peft_lora.ipynb +0 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/image_classification/image_classification_timm_peft_lora.ipynb +0 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/int8_training/Finetune_flan_t5_large_bnb_peft.ipynb +0 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/int8_training/Finetune_opt_bnb_peft.ipynb +0 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/int8_training/config.yaml +19 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/int8_training/fine_tune_blip2_int8.py +104 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/int8_training/peft_adalora_whisper_large_training.py +817 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/int8_training/peft_bnb_whisper_large_v2_training.ipynb +0 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/int8_training/requirements.txt +9 -0
- tasks/tasksmith-ecb1931929df/tests/source/examples/int8_training/run_adalora_whisper_int8.sh +37 -0
tasks/tasksmith-ecb1931929df/tests/source/examples/conditional_generation/peft_lora_seq2seq_accelerate_fsdp.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from accelerate import Accelerator
|
| 5 |
+
from datasets import load_dataset
|
| 6 |
+
from torch.utils.data import DataLoader
|
| 7 |
+
from tqdm import tqdm
|
| 8 |
+
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer, default_data_collator, get_linear_schedule_with_warmup
|
| 9 |
+
|
| 10 |
+
from peft import LoraConfig, TaskType, get_peft_model
|
| 11 |
+
from peft.utils.other import fsdp_auto_wrap_policy
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def main():
|
| 15 |
+
accelerator = Accelerator()
|
| 16 |
+
model_name_or_path = "t5-base"
|
| 17 |
+
batch_size = 8
|
| 18 |
+
text_column = "sentence"
|
| 19 |
+
label_column = "label"
|
| 20 |
+
max_length = 64
|
| 21 |
+
lr = 1e-3
|
| 22 |
+
num_epochs = 1
|
| 23 |
+
base_path = "temp/data/FinancialPhraseBank-v1.0"
|
| 24 |
+
|
| 25 |
+
peft_config = LoraConfig(
|
| 26 |
+
task_type=TaskType.SEQ_2_SEQ_LM, inference_mode=False, r=8, lora_alpha=32, lora_dropout=0.1
|
| 27 |
+
)
|
| 28 |
+
model = AutoModelForSeq2SeqLM.from_pretrained(model_name_or_path)
|
| 29 |
+
model = get_peft_model(model, peft_config)
|
| 30 |
+
accelerator.print(model.print_trainable_parameters())
|
| 31 |
+
|
| 32 |
+
dataset = load_dataset(
|
| 33 |
+
"json",
|
| 34 |
+
data_files={
|
| 35 |
+
"train": os.path.join(base_path, "financial_phrase_bank_train.jsonl"),
|
| 36 |
+
"validation": os.path.join(base_path, "financial_phrase_bank_val.jsonl"),
|
| 37 |
+
},
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name_or_path)
|
| 41 |
+
|
| 42 |
+
def preprocess_function(examples):
|
| 43 |
+
inputs = examples[text_column]
|
| 44 |
+
targets = examples[label_column]
|
| 45 |
+
model_inputs = tokenizer(
|
| 46 |
+
inputs, max_length=max_length, padding="max_length", truncation=True, return_tensors="pt"
|
| 47 |
+
)
|
| 48 |
+
labels = tokenizer(targets, max_length=2, padding="max_length", truncation=True, return_tensors="pt")
|
| 49 |
+
labels = labels["input_ids"]
|
| 50 |
+
labels[labels == tokenizer.pad_token_id] = -100
|
| 51 |
+
model_inputs["labels"] = labels
|
| 52 |
+
return model_inputs
|
| 53 |
+
|
| 54 |
+
with accelerator.main_process_first():
|
| 55 |
+
processed_datasets = dataset.map(
|
| 56 |
+
preprocess_function,
|
| 57 |
+
batched=True,
|
| 58 |
+
num_proc=1,
|
| 59 |
+
remove_columns=dataset["train"].column_names,
|
| 60 |
+
load_from_cache_file=False,
|
| 61 |
+
desc="Running tokenizer on dataset",
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
train_dataset = processed_datasets["train"]
|
| 65 |
+
eval_dataset = processed_datasets["validation"]
|
| 66 |
+
|
| 67 |
+
train_dataloader = DataLoader(
|
| 68 |
+
train_dataset, shuffle=True, collate_fn=default_data_collator, batch_size=batch_size, pin_memory=True
|
| 69 |
+
)
|
| 70 |
+
eval_dataloader = DataLoader(
|
| 71 |
+
eval_dataset, collate_fn=default_data_collator, batch_size=batch_size, pin_memory=True
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
optimizer = torch.optim.AdamW(model.parameters(), lr=lr)
|
| 75 |
+
lr_scheduler = get_linear_schedule_with_warmup(
|
| 76 |
+
optimizer=optimizer,
|
| 77 |
+
num_warmup_steps=0,
|
| 78 |
+
num_training_steps=(len(train_dataloader) * num_epochs),
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
if getattr(accelerator.state, "fsdp_plugin", None) is not None:
|
| 82 |
+
accelerator.state.fsdp_plugin.auto_wrap_policy = fsdp_auto_wrap_policy(model)
|
| 83 |
+
|
| 84 |
+
model, train_dataloader, eval_dataloader, optimizer, lr_scheduler = accelerator.prepare(
|
| 85 |
+
model, train_dataloader, eval_dataloader, optimizer, lr_scheduler
|
| 86 |
+
)
|
| 87 |
+
accelerator.print(model)
|
| 88 |
+
|
| 89 |
+
for epoch in range(num_epochs):
|
| 90 |
+
model.train()
|
| 91 |
+
total_loss = 0
|
| 92 |
+
for step, batch in enumerate(tqdm(train_dataloader)):
|
| 93 |
+
outputs = model(**batch)
|
| 94 |
+
loss = outputs.loss
|
| 95 |
+
total_loss += loss.detach().float()
|
| 96 |
+
loss.backward()
|
| 97 |
+
optimizer.step()
|
| 98 |
+
lr_scheduler.step()
|
| 99 |
+
optimizer.zero_grad()
|
| 100 |
+
|
| 101 |
+
model.eval()
|
| 102 |
+
eval_loss = 0
|
| 103 |
+
eval_preds = []
|
| 104 |
+
for step, batch in enumerate(tqdm(eval_dataloader)):
|
| 105 |
+
with torch.no_grad():
|
| 106 |
+
outputs = model(**batch)
|
| 107 |
+
loss = outputs.loss
|
| 108 |
+
eval_loss += loss.detach().float()
|
| 109 |
+
preds = accelerator.gather_for_metrics(torch.argmax(outputs.logits, -1)).detach().cpu().numpy()
|
| 110 |
+
eval_preds.extend(tokenizer.batch_decode(preds, skip_special_tokens=True))
|
| 111 |
+
eval_epoch_loss = eval_loss / len(eval_dataloader)
|
| 112 |
+
eval_ppl = torch.exp(eval_epoch_loss)
|
| 113 |
+
train_epoch_loss = total_loss / len(train_dataloader)
|
| 114 |
+
train_ppl = torch.exp(train_epoch_loss)
|
| 115 |
+
accelerator.print(f"{epoch=}: {train_ppl=} {train_epoch_loss=} {eval_ppl=} {eval_epoch_loss=}")
|
| 116 |
+
|
| 117 |
+
correct = 0
|
| 118 |
+
total = 0
|
| 119 |
+
for pred, true in zip(eval_preds, dataset["validation"][label_column]):
|
| 120 |
+
if pred.strip() == true.strip():
|
| 121 |
+
correct += 1
|
| 122 |
+
total += 1
|
| 123 |
+
accuracy = correct / total * 100
|
| 124 |
+
accelerator.print(f"{accuracy=}")
|
| 125 |
+
accelerator.print(f"{eval_preds[:10]=}")
|
| 126 |
+
accelerator.print(f"{dataset['validation'][label_column][:10]=}")
|
| 127 |
+
accelerator.wait_for_everyone()
|
| 128 |
+
# Option1: Pushing the model to Hugging Face Hub
|
| 129 |
+
# model.push_to_hub(
|
| 130 |
+
# f"{dataset_name}_{model_name_or_path}_{peft_config.peft_type}_{peft_config.task_type}".replace("/", "_"),
|
| 131 |
+
# token = "hf_..."
|
| 132 |
+
# )
|
| 133 |
+
# token (`bool` or `str`, *optional*):
|
| 134 |
+
# `token` is to be used for HTTP Bearer authorization when accessing remote files. If `True`, will use the token generated
|
| 135 |
+
# when running `huggingface-cli login` (stored in `~/.huggingface`). Will default to `True` if `repo_url`
|
| 136 |
+
# is not specified.
|
| 137 |
+
# Or you can get your token from https://huggingface.co/settings/token
|
| 138 |
+
# Option2: Saving the model locally
|
| 139 |
+
peft_model_id = f"{model_name_or_path}_{peft_config.peft_type}_{peft_config.task_type}".replace("/", "_")
|
| 140 |
+
model.save_pretrained(peft_model_id)
|
| 141 |
+
accelerator.wait_for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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "5f93b7d1",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [],
|
| 9 |
+
"source": [
|
| 10 |
+
"from transformers import AutoModelForSeq2SeqLM\n",
|
| 11 |
+
"from peft import get_peft_config, get_peft_model, get_peft_model_state_dict, PrefixTuningConfig, TaskType\n",
|
| 12 |
+
"import torch\n",
|
| 13 |
+
"from datasets import load_dataset\n",
|
| 14 |
+
"import os\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"os.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\"\n",
|
| 17 |
+
"from transformers import AutoTokenizer\n",
|
| 18 |
+
"from torch.utils.data import DataLoader\n",
|
| 19 |
+
"from transformers import default_data_collator, get_linear_schedule_with_warmup\n",
|
| 20 |
+
"from tqdm import tqdm\n",
|
| 21 |
+
"from datasets import load_dataset\n",
|
| 22 |
+
"\n",
|
| 23 |
+
"device = torch.accelerator.current_accelerator().type if hasattr(torch, \"accelerator\") else \"cuda\"\n",
|
| 24 |
+
"model_name_or_path = \"t5-large\"\n",
|
| 25 |
+
"tokenizer_name_or_path = \"t5-large\"\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"checkpoint_name = \"financial_sentiment_analysis_prefix_tuning_v1.pt\"\n",
|
| 28 |
+
"text_column = \"sentence\"\n",
|
| 29 |
+
"label_column = \"text_label\"\n",
|
| 30 |
+
"max_length = 128\n",
|
| 31 |
+
"lr = 1e-2\n",
|
| 32 |
+
"num_epochs = 5\n",
|
| 33 |
+
"batch_size = 8"
|
| 34 |
+
]
|
| 35 |
+
},
|
| 36 |
+
{
|
| 37 |
+
"cell_type": "code",
|
| 38 |
+
"execution_count": 2,
|
| 39 |
+
"id": "8d0850ac",
|
| 40 |
+
"metadata": {},
|
| 41 |
+
"outputs": [],
|
| 42 |
+
"source": [
|
| 43 |
+
"# creating model\n",
|
| 44 |
+
"peft_config = PrefixTuningConfig(task_type=TaskType.SEQ_2_SEQ_LM, inference_mode=False, num_virtual_tokens=20)\n",
|
| 45 |
+
"\n",
|
| 46 |
+
"model = AutoModelForSeq2SeqLM.from_pretrained(model_name_or_path)\n",
|
| 47 |
+
"model = get_peft_model(model, peft_config)\n",
|
| 48 |
+
"model.print_trainable_parameters()\n",
|
| 49 |
+
"model"
|
| 50 |
+
]
|
| 51 |
+
},
|
| 52 |
+
{
|
| 53 |
+
"cell_type": "code",
|
| 54 |
+
"execution_count": 3,
|
| 55 |
+
"id": "4ee2babf",
|
| 56 |
+
"metadata": {},
|
| 57 |
+
"outputs": [
|
| 58 |
+
{
|
| 59 |
+
"name": "stderr",
|
| 60 |
+
"output_type": "stream",
|
| 61 |
+
"text": [
|
| 62 |
+
"Using the latest cached version of the dataset since financial_phrasebank couldn't be found on the Hugging Face Hub\n",
|
| 63 |
+
"Found the latest cached dataset configuration 'sentences_allagree' at /root/.cache/huggingface/datasets/financial_phrasebank/sentences_allagree/1.0.0/550bde12e6c30e2674da973a55f57edde5181d53f5a5a34c1531c53f93b7e141 (last modified on Thu Jul 31 06:23:15 2025).\n"
|
| 64 |
+
]
|
| 65 |
+
},
|
| 66 |
+
{
|
| 67 |
+
"data": {
|
| 68 |
+
"application/vnd.jupyter.widget-view+json": {
|
| 69 |
+
"model_id": "3b321971d6f942418bd5ef6105a1aa65",
|
| 70 |
+
"version_major": 2,
|
| 71 |
+
"version_minor": 0
|
| 72 |
+
},
|
| 73 |
+
"text/plain": [
|
| 74 |
+
"Map: 0%| | 0/2037 [00:00<?, ? examples/s]"
|
| 75 |
+
]
|
| 76 |
+
},
|
| 77 |
+
"metadata": {},
|
| 78 |
+
"output_type": "display_data"
|
| 79 |
+
},
|
| 80 |
+
{
|
| 81 |
+
"data": {
|
| 82 |
+
"application/vnd.jupyter.widget-view+json": {
|
| 83 |
+
"model_id": "5997543529a849bf97719e59a5ec95b2",
|
| 84 |
+
"version_major": 2,
|
| 85 |
+
"version_minor": 0
|
| 86 |
+
},
|
| 87 |
+
"text/plain": [
|
| 88 |
+
"Map: 0%| | 0/227 [00:00<?, ? examples/s]"
|
| 89 |
+
]
|
| 90 |
+
},
|
| 91 |
+
"metadata": {},
|
| 92 |
+
"output_type": "display_data"
|
| 93 |
+
},
|
| 94 |
+
{
|
| 95 |
+
"data": {
|
| 96 |
+
"text/plain": [
|
| 97 |
+
"{'sentence': \"Progress Group , QPR 's representative in Saudi Arabia and North Africa , has signed a framework agreement for a long term strategic relationship with ISE .\",\n",
|
| 98 |
+
" 'label': 2,\n",
|
| 99 |
+
" 'text_label': 'positive'}"
|
| 100 |
+
]
|
| 101 |
+
},
|
| 102 |
+
"execution_count": 3,
|
| 103 |
+
"metadata": {},
|
| 104 |
+
"output_type": "execute_result"
|
| 105 |
+
}
|
| 106 |
+
],
|
| 107 |
+
"source": [
|
| 108 |
+
"# loading dataset\n",
|
| 109 |
+
"dataset = load_dataset(\"financial_phrasebank\", \"sentences_allagree\")\n",
|
| 110 |
+
"dataset = dataset[\"train\"].train_test_split(test_size=0.1)\n",
|
| 111 |
+
"dataset[\"validation\"] = dataset[\"test\"]\n",
|
| 112 |
+
"del dataset[\"test\"]\n",
|
| 113 |
+
"\n",
|
| 114 |
+
"classes = dataset[\"train\"].features[\"label\"].names\n",
|
| 115 |
+
"dataset = dataset.map(\n",
|
| 116 |
+
" lambda x: {\"text_label\": [classes[label] for label in x[\"label\"]]},\n",
|
| 117 |
+
" batched=True,\n",
|
| 118 |
+
" num_proc=1,\n",
|
| 119 |
+
")\n",
|
| 120 |
+
"\n",
|
| 121 |
+
"dataset[\"train\"][0]"
|
| 122 |
+
]
|
| 123 |
+
},
|
| 124 |
+
{
|
| 125 |
+
"cell_type": "code",
|
| 126 |
+
"execution_count": 4,
|
| 127 |
+
"id": "adf9608c",
|
| 128 |
+
"metadata": {},
|
| 129 |
+
"outputs": [
|
| 130 |
+
{
|
| 131 |
+
"data": {
|
| 132 |
+
"application/vnd.jupyter.widget-view+json": {
|
| 133 |
+
"model_id": "ee9bf13a2e3f4812a51a87346a4614f3",
|
| 134 |
+
"version_major": 2,
|
| 135 |
+
"version_minor": 0
|
| 136 |
+
},
|
| 137 |
+
"text/plain": [
|
| 138 |
+
"spiece.model: 0%| | 0.00/792k [00:00<?, ?B/s]"
|
| 139 |
+
]
|
| 140 |
+
},
|
| 141 |
+
"metadata": {},
|
| 142 |
+
"output_type": "display_data"
|
| 143 |
+
},
|
| 144 |
+
{
|
| 145 |
+
"data": {
|
| 146 |
+
"application/vnd.jupyter.widget-view+json": {
|
| 147 |
+
"model_id": "332fcaa33dc343e7a20b24cec7ec97e9",
|
| 148 |
+
"version_major": 2,
|
| 149 |
+
"version_minor": 0
|
| 150 |
+
},
|
| 151 |
+
"text/plain": [
|
| 152 |
+
"tokenizer.json: 0%| | 0.00/1.39M [00:00<?, ?B/s]"
|
| 153 |
+
]
|
| 154 |
+
},
|
| 155 |
+
"metadata": {},
|
| 156 |
+
"output_type": "display_data"
|
| 157 |
+
},
|
| 158 |
+
{
|
| 159 |
+
"data": {
|
| 160 |
+
"application/vnd.jupyter.widget-view+json": {
|
| 161 |
+
"model_id": "a2135262c7a44377b35fe32b8d86d6c6",
|
| 162 |
+
"version_major": 2,
|
| 163 |
+
"version_minor": 0
|
| 164 |
+
},
|
| 165 |
+
"text/plain": [
|
| 166 |
+
"Running tokenizer on dataset: 0%| | 0/2037 [00:00<?, ? examples/s]"
|
| 167 |
+
]
|
| 168 |
+
},
|
| 169 |
+
"metadata": {},
|
| 170 |
+
"output_type": "display_data"
|
| 171 |
+
},
|
| 172 |
+
{
|
| 173 |
+
"data": {
|
| 174 |
+
"application/vnd.jupyter.widget-view+json": {
|
| 175 |
+
"model_id": "dc8598b160484939b27c65be001c694c",
|
| 176 |
+
"version_major": 2,
|
| 177 |
+
"version_minor": 0
|
| 178 |
+
},
|
| 179 |
+
"text/plain": [
|
| 180 |
+
"Running tokenizer on dataset: 0%| | 0/227 [00:00<?, ? examples/s]"
|
| 181 |
+
]
|
| 182 |
+
},
|
| 183 |
+
"metadata": {},
|
| 184 |
+
"output_type": "display_data"
|
| 185 |
+
}
|
| 186 |
+
],
|
| 187 |
+
"source": [
|
| 188 |
+
"# data preprocessing\n",
|
| 189 |
+
"tokenizer = AutoTokenizer.from_pretrained(model_name_or_path)\n",
|
| 190 |
+
"\n",
|
| 191 |
+
"\n",
|
| 192 |
+
"def preprocess_function(examples):\n",
|
| 193 |
+
" inputs = examples[text_column]\n",
|
| 194 |
+
" targets = examples[label_column]\n",
|
| 195 |
+
" model_inputs = tokenizer(inputs, max_length=max_length, padding=\"max_length\", truncation=True, return_tensors=\"pt\")\n",
|
| 196 |
+
" labels = tokenizer(targets, max_length=2, padding=\"max_length\", truncation=True, return_tensors=\"pt\")\n",
|
| 197 |
+
" labels = labels[\"input_ids\"]\n",
|
| 198 |
+
" labels[labels == tokenizer.pad_token_id] = -100\n",
|
| 199 |
+
" model_inputs[\"labels\"] = labels\n",
|
| 200 |
+
" return model_inputs\n",
|
| 201 |
+
"\n",
|
| 202 |
+
"\n",
|
| 203 |
+
"processed_datasets = dataset.map(\n",
|
| 204 |
+
" preprocess_function,\n",
|
| 205 |
+
" batched=True,\n",
|
| 206 |
+
" num_proc=1,\n",
|
| 207 |
+
" remove_columns=dataset[\"train\"].column_names,\n",
|
| 208 |
+
" load_from_cache_file=False,\n",
|
| 209 |
+
" desc=\"Running tokenizer on dataset\",\n",
|
| 210 |
+
")\n",
|
| 211 |
+
"\n",
|
| 212 |
+
"train_dataset = processed_datasets[\"train\"]\n",
|
| 213 |
+
"eval_dataset = processed_datasets[\"validation\"]\n",
|
| 214 |
+
"\n",
|
| 215 |
+
"train_dataloader = DataLoader(\n",
|
| 216 |
+
" train_dataset, shuffle=True, collate_fn=default_data_collator, batch_size=batch_size, pin_memory=True\n",
|
| 217 |
+
")\n",
|
| 218 |
+
"eval_dataloader = DataLoader(eval_dataset, collate_fn=default_data_collator, batch_size=batch_size, pin_memory=True)"
|
| 219 |
+
]
|
| 220 |
+
},
|
| 221 |
+
{
|
| 222 |
+
"cell_type": "code",
|
| 223 |
+
"execution_count": 5,
|
| 224 |
+
"id": "f733a3c6",
|
| 225 |
+
"metadata": {},
|
| 226 |
+
"outputs": [],
|
| 227 |
+
"source": [
|
| 228 |
+
"# optimizer and lr scheduler\n",
|
| 229 |
+
"optimizer = torch.optim.AdamW(model.parameters(), lr=lr)\n",
|
| 230 |
+
"lr_scheduler = get_linear_schedule_with_warmup(\n",
|
| 231 |
+
" optimizer=optimizer,\n",
|
| 232 |
+
" num_warmup_steps=0,\n",
|
| 233 |
+
" num_training_steps=(len(train_dataloader) * num_epochs),\n",
|
| 234 |
+
")"
|
| 235 |
+
]
|
| 236 |
+
},
|
| 237 |
+
{
|
| 238 |
+
"cell_type": "code",
|
| 239 |
+
"execution_count": null,
|
| 240 |
+
"id": "6b3a4090",
|
| 241 |
+
"metadata": {},
|
| 242 |
+
"outputs": [],
|
| 243 |
+
"source": [
|
| 244 |
+
"# training and evaluation\n",
|
| 245 |
+
"model = model.to(device)\n",
|
| 246 |
+
"\n",
|
| 247 |
+
"for epoch in range(num_epochs):\n",
|
| 248 |
+
" model.train()\n",
|
| 249 |
+
" total_loss = 0\n",
|
| 250 |
+
" for step, batch in enumerate(tqdm(train_dataloader)):\n",
|
| 251 |
+
" batch = {k: v.to(device) for k, v in batch.items()}\n",
|
| 252 |
+
" outputs = model(**batch)\n",
|
| 253 |
+
" loss = outputs.loss\n",
|
| 254 |
+
" total_loss += loss.detach().float()\n",
|
| 255 |
+
" loss.backward()\n",
|
| 256 |
+
" optimizer.step()\n",
|
| 257 |
+
" lr_scheduler.step()\n",
|
| 258 |
+
" optimizer.zero_grad()\n",
|
| 259 |
+
"\n",
|
| 260 |
+
" model.eval()\n",
|
| 261 |
+
" eval_loss = 0\n",
|
| 262 |
+
" eval_preds = []\n",
|
| 263 |
+
" for step, batch in enumerate(tqdm(eval_dataloader)):\n",
|
| 264 |
+
" batch = {k: v.to(device) for k, v in batch.items()}\n",
|
| 265 |
+
" with torch.no_grad():\n",
|
| 266 |
+
" outputs = model(**batch)\n",
|
| 267 |
+
" loss = outputs.loss\n",
|
| 268 |
+
" eval_loss += loss.detach().float()\n",
|
| 269 |
+
" eval_preds.extend(\n",
|
| 270 |
+
" tokenizer.batch_decode(torch.argmax(outputs.logits, -1).detach().cpu().numpy(), skip_special_tokens=True)\n",
|
| 271 |
+
" )\n",
|
| 272 |
+
"\n",
|
| 273 |
+
" eval_epoch_loss = eval_loss / len(eval_dataloader)\n",
|
| 274 |
+
" eval_ppl = torch.exp(eval_epoch_loss)\n",
|
| 275 |
+
" train_epoch_loss = total_loss / len(train_dataloader)\n",
|
| 276 |
+
" train_ppl = torch.exp(train_epoch_loss)\n",
|
| 277 |
+
" print(f\"{epoch=}: {train_ppl=} {train_epoch_loss=} {eval_ppl=} {eval_epoch_loss=}\")"
|
| 278 |
+
]
|
| 279 |
+
},
|
| 280 |
+
{
|
| 281 |
+
"cell_type": "code",
|
| 282 |
+
"execution_count": 7,
|
| 283 |
+
"id": "6cafa67b",
|
| 284 |
+
"metadata": {},
|
| 285 |
+
"outputs": [
|
| 286 |
+
{
|
| 287 |
+
"name": "stdout",
|
| 288 |
+
"output_type": "stream",
|
| 289 |
+
"text": [
|
| 290 |
+
"accuracy=96.91629955947137 % on the evaluation dataset\n",
|
| 291 |
+
"eval_preds[:10]=['negative', 'positive', 'neutral', 'neutral', 'neutral', 'neutral', 'neutral', 'neutral', 'neutral', 'neutral']\n",
|
| 292 |
+
"dataset['validation']['text_label'][:10]=['negative', 'neutral', 'neutral', 'neutral', 'neutral', 'neutral', 'neutral', 'neutral', 'neutral', 'neutral']\n"
|
| 293 |
+
]
|
| 294 |
+
}
|
| 295 |
+
],
|
| 296 |
+
"source": [
|
| 297 |
+
"# print accuracy\n",
|
| 298 |
+
"correct = 0\n",
|
| 299 |
+
"total = 0\n",
|
| 300 |
+
"for pred, true in zip(eval_preds, dataset[\"validation\"][\"text_label\"]):\n",
|
| 301 |
+
" if pred.strip() == true.strip():\n",
|
| 302 |
+
" correct += 1\n",
|
| 303 |
+
" total += 1\n",
|
| 304 |
+
"accuracy = correct / total * 100\n",
|
| 305 |
+
"print(f\"{accuracy=} % on the evaluation dataset\")\n",
|
| 306 |
+
"print(f\"{eval_preds[:10]=}\")\n",
|
| 307 |
+
"print(f\"{dataset['validation']['text_label'][:10]=}\")"
|
| 308 |
+
]
|
| 309 |
+
},
|
| 310 |
+
{
|
| 311 |
+
"cell_type": "code",
|
| 312 |
+
"execution_count": 8,
|
| 313 |
+
"id": "a8de6005",
|
| 314 |
+
"metadata": {},
|
| 315 |
+
"outputs": [],
|
| 316 |
+
"source": [
|
| 317 |
+
"# saving model\n",
|
| 318 |
+
"peft_model_id = f\"{model_name_or_path}_{peft_config.peft_type}_{peft_config.task_type}\"\n",
|
| 319 |
+
"model.save_pretrained(peft_model_id)"
|
| 320 |
+
]
|
| 321 |
+
},
|
| 322 |
+
{
|
| 323 |
+
"cell_type": "code",
|
| 324 |
+
"execution_count": null,
|
| 325 |
+
"id": "bd20cd4c",
|
| 326 |
+
"metadata": {},
|
| 327 |
+
"outputs": [
|
| 328 |
+
{
|
| 329 |
+
"name": "stdout",
|
| 330 |
+
"output_type": "stream",
|
| 331 |
+
"text": [
|
| 332 |
+
"3,8M\tt5-large_PREFIX_TUNING_SEQ_2_SEQ_LM/adapter_model.safetensors\r\n"
|
| 333 |
+
]
|
| 334 |
+
}
|
| 335 |
+
],
|
| 336 |
+
"source": [
|
| 337 |
+
"ckpt = f\"{peft_model_id}/adapter_model.safetensors\"\n",
|
| 338 |
+
"!du -h $ckpt"
|
| 339 |
+
]
|
| 340 |
+
},
|
| 341 |
+
{
|
| 342 |
+
"cell_type": "code",
|
| 343 |
+
"execution_count": 11,
|
| 344 |
+
"id": "76c2fc29",
|
| 345 |
+
"metadata": {},
|
| 346 |
+
"outputs": [],
|
| 347 |
+
"source": [
|
| 348 |
+
"from peft import PeftModel, PeftConfig\n",
|
| 349 |
+
"\n",
|
| 350 |
+
"peft_model_id = f\"{model_name_or_path}_{peft_config.peft_type}_{peft_config.task_type}\"\n",
|
| 351 |
+
"\n",
|
| 352 |
+
"config = PeftConfig.from_pretrained(peft_model_id)\n",
|
| 353 |
+
"model = AutoModelForSeq2SeqLM.from_pretrained(config.base_model_name_or_path)\n",
|
| 354 |
+
"model = PeftModel.from_pretrained(model, peft_model_id)"
|
| 355 |
+
]
|
| 356 |
+
},
|
| 357 |
+
{
|
| 358 |
+
"cell_type": "code",
|
| 359 |
+
"execution_count": 27,
|
| 360 |
+
"id": "d997f1cc",
|
| 361 |
+
"metadata": {},
|
| 362 |
+
"outputs": [
|
| 363 |
+
{
|
| 364 |
+
"name": "stdout",
|
| 365 |
+
"output_type": "stream",
|
| 366 |
+
"text": [
|
| 367 |
+
"Acando AB ( ACANB SS ) fell 8.9 percent to 13.35 kronor , the lowest close since Dec. 11 .\n",
|
| 368 |
+
"{'input_ids': tensor([[ 4292, 232, 32, 3, 5359, 41, 3, 22029, 14972, 3,\n",
|
| 369 |
+
" 4256, 3, 61, 4728, 4848, 1298, 1093, 12, 8808, 2469,\n",
|
| 370 |
+
" 3, 22318, 29, 127, 3, 6, 8, 7402, 885, 437,\n",
|
| 371 |
+
" 4451, 5, 850, 3, 5, 1]]), 'attention_mask': tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n",
|
| 372 |
+
" 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])}\n",
|
| 373 |
+
"tensor([[ 0, 2841, 1]])\n",
|
| 374 |
+
"['negative']\n"
|
| 375 |
+
]
|
| 376 |
+
}
|
| 377 |
+
],
|
| 378 |
+
"source": [
|
| 379 |
+
"model.eval()\n",
|
| 380 |
+
"i = 107\n",
|
| 381 |
+
"inputs = tokenizer(dataset[\"validation\"][text_column][i], return_tensors=\"pt\")\n",
|
| 382 |
+
"print(dataset[\"validation\"][text_column][i])\n",
|
| 383 |
+
"print(inputs)\n",
|
| 384 |
+
"\n",
|
| 385 |
+
"with torch.no_grad():\n",
|
| 386 |
+
" outputs = model.generate(input_ids=inputs[\"input_ids\"], max_new_tokens=10)\n",
|
| 387 |
+
" print(outputs)\n",
|
| 388 |
+
" print(tokenizer.batch_decode(outputs.detach().cpu().numpy(), skip_special_tokens=True))"
|
| 389 |
+
]
|
| 390 |
+
},
|
| 391 |
+
{
|
| 392 |
+
"cell_type": "code",
|
| 393 |
+
"execution_count": null,
|
| 394 |
+
"id": "fb746c1e",
|
| 395 |
+
"metadata": {},
|
| 396 |
+
"outputs": [],
|
| 397 |
+
"source": []
|
| 398 |
+
}
|
| 399 |
+
],
|
| 400 |
+
"metadata": {
|
| 401 |
+
"kernelspec": {
|
| 402 |
+
"display_name": "Python 3 (ipykernel)",
|
| 403 |
+
"language": "python",
|
| 404 |
+
"name": "python3"
|
| 405 |
+
},
|
| 406 |
+
"language_info": {
|
| 407 |
+
"codemirror_mode": {
|
| 408 |
+
"name": "ipython",
|
| 409 |
+
"version": 3
|
| 410 |
+
},
|
| 411 |
+
"file_extension": ".py",
|
| 412 |
+
"mimetype": "text/x-python",
|
| 413 |
+
"name": "python",
|
| 414 |
+
"nbconvert_exporter": "python",
|
| 415 |
+
"pygments_lexer": "ipython3",
|
| 416 |
+
"version": "3.11.13"
|
| 417 |
+
},
|
| 418 |
+
"vscode": {
|
| 419 |
+
"interpreter": {
|
| 420 |
+
"hash": "aee8b7b246df8f9039afb4144a1f6fd8d2ca17a180786b69acc140d282b71a49"
|
| 421 |
+
}
|
| 422 |
+
}
|
| 423 |
+
},
|
| 424 |
+
"nbformat": 4,
|
| 425 |
+
"nbformat_minor": 5
|
| 426 |
+
}
|
tasks/tasksmith-ecb1931929df/tests/source/examples/conditional_generation/peft_prompt_tuning_seq2seq.ipynb
ADDED
|
@@ -0,0 +1,653 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "5f93b7d1",
|
| 7 |
+
"metadata": {
|
| 8 |
+
"ExecuteTime": {
|
| 9 |
+
"end_time": "2023-05-30T08:37:58.711225Z",
|
| 10 |
+
"start_time": "2023-05-30T08:37:56.881307Z"
|
| 11 |
+
}
|
| 12 |
+
},
|
| 13 |
+
"outputs": [],
|
| 14 |
+
"source": [
|
| 15 |
+
"import os\n",
|
| 16 |
+
"\n",
|
| 17 |
+
"import torch\n",
|
| 18 |
+
"from transformers import AutoModelForSeq2SeqLM, AutoTokenizer, default_data_collator, get_linear_schedule_with_warmup\n",
|
| 19 |
+
"from peft import get_peft_model, PromptTuningConfig, TaskType, PromptTuningInit\n",
|
| 20 |
+
"from torch.utils.data import DataLoader\n",
|
| 21 |
+
"from tqdm import tqdm\n",
|
| 22 |
+
"from datasets import load_dataset\n",
|
| 23 |
+
"\n",
|
| 24 |
+
"os.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\"\n",
|
| 25 |
+
"\n",
|
| 26 |
+
"device = torch.accelerator.current_accelerator().type if hasattr(torch, \"accelerator\") else \"cuda\"\n",
|
| 27 |
+
"model_name_or_path = \"t5-large\"\n",
|
| 28 |
+
"tokenizer_name_or_path = \"t5-large\"\n",
|
| 29 |
+
"\n",
|
| 30 |
+
"checkpoint_name = \"financial_sentiment_analysis_prompt_tuning_v1.pt\"\n",
|
| 31 |
+
"text_column = \"sentence\"\n",
|
| 32 |
+
"label_column = \"text_label\"\n",
|
| 33 |
+
"max_length = 128\n",
|
| 34 |
+
"lr = 1\n",
|
| 35 |
+
"num_epochs = 5\n",
|
| 36 |
+
"batch_size = 8"
|
| 37 |
+
]
|
| 38 |
+
},
|
| 39 |
+
{
|
| 40 |
+
"cell_type": "code",
|
| 41 |
+
"execution_count": 2,
|
| 42 |
+
"id": "8d0850ac",
|
| 43 |
+
"metadata": {
|
| 44 |
+
"ExecuteTime": {
|
| 45 |
+
"end_time": "2023-05-30T08:38:12.413984Z",
|
| 46 |
+
"start_time": "2023-05-30T08:38:04.601042Z"
|
| 47 |
+
}
|
| 48 |
+
},
|
| 49 |
+
"outputs": [
|
| 50 |
+
{
|
| 51 |
+
"name": "stdout",
|
| 52 |
+
"output_type": "stream",
|
| 53 |
+
"text": [
|
| 54 |
+
"trainable params: 40,960 || all params: 737,709,056 || trainable%: 0.0056\n"
|
| 55 |
+
]
|
| 56 |
+
},
|
| 57 |
+
{
|
| 58 |
+
"data": {
|
| 59 |
+
"text/plain": [
|
| 60 |
+
"PeftModelForSeq2SeqLM(\n",
|
| 61 |
+
" (base_model): T5ForConditionalGeneration(\n",
|
| 62 |
+
" (shared): Embedding(32128, 1024)\n",
|
| 63 |
+
" (encoder): T5Stack(\n",
|
| 64 |
+
" (embed_tokens): Embedding(32128, 1024)\n",
|
| 65 |
+
" (block): ModuleList(\n",
|
| 66 |
+
" (0): T5Block(\n",
|
| 67 |
+
" (layer): ModuleList(\n",
|
| 68 |
+
" (0): T5LayerSelfAttention(\n",
|
| 69 |
+
" (SelfAttention): T5Attention(\n",
|
| 70 |
+
" (q): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 71 |
+
" (k): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 72 |
+
" (v): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 73 |
+
" (o): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 74 |
+
" (relative_attention_bias): Embedding(32, 16)\n",
|
| 75 |
+
" )\n",
|
| 76 |
+
" (layer_norm): T5LayerNorm()\n",
|
| 77 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
| 78 |
+
" )\n",
|
| 79 |
+
" (1): T5LayerFF(\n",
|
| 80 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
| 81 |
+
" (wi): Linear(in_features=1024, out_features=4096, bias=False)\n",
|
| 82 |
+
" (wo): Linear(in_features=4096, out_features=1024, bias=False)\n",
|
| 83 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
| 84 |
+
" (act): ReLU()\n",
|
| 85 |
+
" )\n",
|
| 86 |
+
" (layer_norm): T5LayerNorm()\n",
|
| 87 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
| 88 |
+
" )\n",
|
| 89 |
+
" )\n",
|
| 90 |
+
" )\n",
|
| 91 |
+
" (1-23): 23 x T5Block(\n",
|
| 92 |
+
" (layer): ModuleList(\n",
|
| 93 |
+
" (0): T5LayerSelfAttention(\n",
|
| 94 |
+
" (SelfAttention): T5Attention(\n",
|
| 95 |
+
" (q): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 96 |
+
" (k): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 97 |
+
" (v): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 98 |
+
" (o): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 99 |
+
" )\n",
|
| 100 |
+
" (layer_norm): T5LayerNorm()\n",
|
| 101 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
| 102 |
+
" )\n",
|
| 103 |
+
" (1): T5LayerFF(\n",
|
| 104 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
| 105 |
+
" (wi): Linear(in_features=1024, out_features=4096, bias=False)\n",
|
| 106 |
+
" (wo): Linear(in_features=4096, out_features=1024, bias=False)\n",
|
| 107 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
| 108 |
+
" (act): ReLU()\n",
|
| 109 |
+
" )\n",
|
| 110 |
+
" (layer_norm): T5LayerNorm()\n",
|
| 111 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
| 112 |
+
" )\n",
|
| 113 |
+
" )\n",
|
| 114 |
+
" )\n",
|
| 115 |
+
" )\n",
|
| 116 |
+
" (final_layer_norm): T5LayerNorm()\n",
|
| 117 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
| 118 |
+
" )\n",
|
| 119 |
+
" (decoder): T5Stack(\n",
|
| 120 |
+
" (embed_tokens): Embedding(32128, 1024)\n",
|
| 121 |
+
" (block): ModuleList(\n",
|
| 122 |
+
" (0): T5Block(\n",
|
| 123 |
+
" (layer): ModuleList(\n",
|
| 124 |
+
" (0): T5LayerSelfAttention(\n",
|
| 125 |
+
" (SelfAttention): T5Attention(\n",
|
| 126 |
+
" (q): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 127 |
+
" (k): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 128 |
+
" (v): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 129 |
+
" (o): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 130 |
+
" (relative_attention_bias): Embedding(32, 16)\n",
|
| 131 |
+
" )\n",
|
| 132 |
+
" (layer_norm): T5LayerNorm()\n",
|
| 133 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
| 134 |
+
" )\n",
|
| 135 |
+
" (1): T5LayerCrossAttention(\n",
|
| 136 |
+
" (EncDecAttention): T5Attention(\n",
|
| 137 |
+
" (q): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 138 |
+
" (k): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 139 |
+
" (v): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 140 |
+
" (o): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 141 |
+
" )\n",
|
| 142 |
+
" (layer_norm): T5LayerNorm()\n",
|
| 143 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
| 144 |
+
" )\n",
|
| 145 |
+
" (2): T5LayerFF(\n",
|
| 146 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
| 147 |
+
" (wi): Linear(in_features=1024, out_features=4096, bias=False)\n",
|
| 148 |
+
" (wo): Linear(in_features=4096, out_features=1024, bias=False)\n",
|
| 149 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
| 150 |
+
" (act): ReLU()\n",
|
| 151 |
+
" )\n",
|
| 152 |
+
" (layer_norm): T5LayerNorm()\n",
|
| 153 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
| 154 |
+
" )\n",
|
| 155 |
+
" )\n",
|
| 156 |
+
" )\n",
|
| 157 |
+
" (1-23): 23 x T5Block(\n",
|
| 158 |
+
" (layer): ModuleList(\n",
|
| 159 |
+
" (0): T5LayerSelfAttention(\n",
|
| 160 |
+
" (SelfAttention): T5Attention(\n",
|
| 161 |
+
" (q): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 162 |
+
" (k): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 163 |
+
" (v): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 164 |
+
" (o): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 165 |
+
" )\n",
|
| 166 |
+
" (layer_norm): T5LayerNorm()\n",
|
| 167 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
| 168 |
+
" )\n",
|
| 169 |
+
" (1): T5LayerCrossAttention(\n",
|
| 170 |
+
" (EncDecAttention): T5Attention(\n",
|
| 171 |
+
" (q): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 172 |
+
" (k): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 173 |
+
" (v): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 174 |
+
" (o): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 175 |
+
" )\n",
|
| 176 |
+
" (layer_norm): T5LayerNorm()\n",
|
| 177 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
| 178 |
+
" )\n",
|
| 179 |
+
" (2): T5LayerFF(\n",
|
| 180 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
| 181 |
+
" (wi): Linear(in_features=1024, out_features=4096, bias=False)\n",
|
| 182 |
+
" (wo): Linear(in_features=4096, out_features=1024, bias=False)\n",
|
| 183 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
| 184 |
+
" (act): ReLU()\n",
|
| 185 |
+
" )\n",
|
| 186 |
+
" (layer_norm): T5LayerNorm()\n",
|
| 187 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
| 188 |
+
" )\n",
|
| 189 |
+
" )\n",
|
| 190 |
+
" )\n",
|
| 191 |
+
" )\n",
|
| 192 |
+
" (final_layer_norm): T5LayerNorm()\n",
|
| 193 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
| 194 |
+
" )\n",
|
| 195 |
+
" (lm_head): Linear(in_features=1024, out_features=32128, bias=False)\n",
|
| 196 |
+
" )\n",
|
| 197 |
+
" (prompt_encoder): ModuleDict(\n",
|
| 198 |
+
" (default): PromptEmbedding(\n",
|
| 199 |
+
" (embedding): Embedding(40, 1024)\n",
|
| 200 |
+
" )\n",
|
| 201 |
+
" )\n",
|
| 202 |
+
" (word_embeddings): Embedding(32128, 1024)\n",
|
| 203 |
+
")"
|
| 204 |
+
]
|
| 205 |
+
},
|
| 206 |
+
"execution_count": 2,
|
| 207 |
+
"metadata": {},
|
| 208 |
+
"output_type": "execute_result"
|
| 209 |
+
}
|
| 210 |
+
],
|
| 211 |
+
"source": [
|
| 212 |
+
"# creating model\n",
|
| 213 |
+
"peft_config = PromptTuningConfig(\n",
|
| 214 |
+
" task_type=TaskType.SEQ_2_SEQ_LM,\n",
|
| 215 |
+
" prompt_tuning_init=PromptTuningInit.TEXT,\n",
|
| 216 |
+
" num_virtual_tokens=20,\n",
|
| 217 |
+
" prompt_tuning_init_text=\"What is the sentiment of this article?\\n\",\n",
|
| 218 |
+
" inference_mode=False,\n",
|
| 219 |
+
" tokenizer_name_or_path=model_name_or_path,\n",
|
| 220 |
+
")\n",
|
| 221 |
+
"\n",
|
| 222 |
+
"model = AutoModelForSeq2SeqLM.from_pretrained(model_name_or_path)\n",
|
| 223 |
+
"model = get_peft_model(model, peft_config)\n",
|
| 224 |
+
"model.print_trainable_parameters()\n",
|
| 225 |
+
"model"
|
| 226 |
+
]
|
| 227 |
+
},
|
| 228 |
+
{
|
| 229 |
+
"cell_type": "code",
|
| 230 |
+
"execution_count": 3,
|
| 231 |
+
"id": "4ee2babf",
|
| 232 |
+
"metadata": {
|
| 233 |
+
"ExecuteTime": {
|
| 234 |
+
"end_time": "2023-05-30T08:38:18.759143Z",
|
| 235 |
+
"start_time": "2023-05-30T08:38:17.881621Z"
|
| 236 |
+
}
|
| 237 |
+
},
|
| 238 |
+
"outputs": [
|
| 239 |
+
{
|
| 240 |
+
"name": "stderr",
|
| 241 |
+
"output_type": "stream",
|
| 242 |
+
"text": [
|
| 243 |
+
"Using the latest cached version of the dataset since financial_phrasebank couldn't be found on the Hugging Face Hub\n",
|
| 244 |
+
"Found the latest cached dataset configuration 'sentences_allagree' at /root/.cache/huggingface/datasets/financial_phrasebank/sentences_allagree/1.0.0/550bde12e6c30e2674da973a55f57edde5181d53f5a5a34c1531c53f93b7e141 (last modified on Thu Jul 31 06:37:38 2025).\n"
|
| 245 |
+
]
|
| 246 |
+
},
|
| 247 |
+
{
|
| 248 |
+
"data": {
|
| 249 |
+
"application/vnd.jupyter.widget-view+json": {
|
| 250 |
+
"model_id": "2b64258700bd40548ddcd626f3920c9a",
|
| 251 |
+
"version_major": 2,
|
| 252 |
+
"version_minor": 0
|
| 253 |
+
},
|
| 254 |
+
"text/plain": [
|
| 255 |
+
"Map: 0%| | 0/2037 [00:00<?, ? examples/s]"
|
| 256 |
+
]
|
| 257 |
+
},
|
| 258 |
+
"metadata": {},
|
| 259 |
+
"output_type": "display_data"
|
| 260 |
+
},
|
| 261 |
+
{
|
| 262 |
+
"data": {
|
| 263 |
+
"application/vnd.jupyter.widget-view+json": {
|
| 264 |
+
"model_id": "d95de9b1dc3d417da35118c14d02b986",
|
| 265 |
+
"version_major": 2,
|
| 266 |
+
"version_minor": 0
|
| 267 |
+
},
|
| 268 |
+
"text/plain": [
|
| 269 |
+
"Map: 0%| | 0/227 [00:00<?, ? examples/s]"
|
| 270 |
+
]
|
| 271 |
+
},
|
| 272 |
+
"metadata": {},
|
| 273 |
+
"output_type": "display_data"
|
| 274 |
+
},
|
| 275 |
+
{
|
| 276 |
+
"data": {
|
| 277 |
+
"text/plain": [
|
| 278 |
+
"{'sentence': 'The 2500-passenger ferry will have dimensions of 185 m length overall , 170 m length between perpendiculars , 27.70 m breadth and 6.55 m design draught .',\n",
|
| 279 |
+
" 'label': 1,\n",
|
| 280 |
+
" 'text_label': 'neutral'}"
|
| 281 |
+
]
|
| 282 |
+
},
|
| 283 |
+
"execution_count": 3,
|
| 284 |
+
"metadata": {},
|
| 285 |
+
"output_type": "execute_result"
|
| 286 |
+
}
|
| 287 |
+
],
|
| 288 |
+
"source": [
|
| 289 |
+
"# loading dataset\n",
|
| 290 |
+
"dataset = load_dataset(\"financial_phrasebank\", \"sentences_allagree\")\n",
|
| 291 |
+
"dataset = dataset[\"train\"].train_test_split(test_size=0.1)\n",
|
| 292 |
+
"dataset[\"validation\"] = dataset[\"test\"]\n",
|
| 293 |
+
"del dataset[\"test\"]\n",
|
| 294 |
+
"\n",
|
| 295 |
+
"classes = dataset[\"train\"].features[\"label\"].names\n",
|
| 296 |
+
"dataset = dataset.map(\n",
|
| 297 |
+
" lambda x: {\"text_label\": [classes[label] for label in x[\"label\"]]},\n",
|
| 298 |
+
" batched=True,\n",
|
| 299 |
+
" num_proc=1,\n",
|
| 300 |
+
")\n",
|
| 301 |
+
"\n",
|
| 302 |
+
"dataset[\"train\"][0]"
|
| 303 |
+
]
|
| 304 |
+
},
|
| 305 |
+
{
|
| 306 |
+
"cell_type": "code",
|
| 307 |
+
"execution_count": 4,
|
| 308 |
+
"id": "adf9608c",
|
| 309 |
+
"metadata": {
|
| 310 |
+
"ExecuteTime": {
|
| 311 |
+
"end_time": "2023-05-30T08:38:21.132266Z",
|
| 312 |
+
"start_time": "2023-05-30T08:38:20.340722Z"
|
| 313 |
+
}
|
| 314 |
+
},
|
| 315 |
+
"outputs": [
|
| 316 |
+
{
|
| 317 |
+
"data": {
|
| 318 |
+
"application/vnd.jupyter.widget-view+json": {
|
| 319 |
+
"model_id": "a78b4b1a041546248b8e6703eaec0969",
|
| 320 |
+
"version_major": 2,
|
| 321 |
+
"version_minor": 0
|
| 322 |
+
},
|
| 323 |
+
"text/plain": [
|
| 324 |
+
"Running tokenizer on dataset: 0%| | 0/2037 [00:00<?, ? examples/s]"
|
| 325 |
+
]
|
| 326 |
+
},
|
| 327 |
+
"metadata": {},
|
| 328 |
+
"output_type": "display_data"
|
| 329 |
+
},
|
| 330 |
+
{
|
| 331 |
+
"data": {
|
| 332 |
+
"application/vnd.jupyter.widget-view+json": {
|
| 333 |
+
"model_id": "bbe2962a25144b5488c297e186df824f",
|
| 334 |
+
"version_major": 2,
|
| 335 |
+
"version_minor": 0
|
| 336 |
+
},
|
| 337 |
+
"text/plain": [
|
| 338 |
+
"Running tokenizer on dataset: 0%| | 0/227 [00:00<?, ? examples/s]"
|
| 339 |
+
]
|
| 340 |
+
},
|
| 341 |
+
"metadata": {},
|
| 342 |
+
"output_type": "display_data"
|
| 343 |
+
}
|
| 344 |
+
],
|
| 345 |
+
"source": [
|
| 346 |
+
"# data preprocessing\n",
|
| 347 |
+
"tokenizer = AutoTokenizer.from_pretrained(model_name_or_path)\n",
|
| 348 |
+
"target_max_length = max([len(tokenizer(class_label)[\"input_ids\"]) for class_label in classes])\n",
|
| 349 |
+
"\n",
|
| 350 |
+
"\n",
|
| 351 |
+
"def preprocess_function(examples):\n",
|
| 352 |
+
" inputs = examples[text_column]\n",
|
| 353 |
+
" targets = examples[label_column]\n",
|
| 354 |
+
" model_inputs = tokenizer(inputs, max_length=max_length, padding=\"max_length\", truncation=True, return_tensors=\"pt\")\n",
|
| 355 |
+
" labels = tokenizer(\n",
|
| 356 |
+
" targets, max_length=target_max_length, padding=\"max_length\", truncation=True, return_tensors=\"pt\"\n",
|
| 357 |
+
" )\n",
|
| 358 |
+
" labels = labels[\"input_ids\"]\n",
|
| 359 |
+
" labels[labels == tokenizer.pad_token_id] = -100\n",
|
| 360 |
+
" model_inputs[\"labels\"] = labels\n",
|
| 361 |
+
" return model_inputs\n",
|
| 362 |
+
"\n",
|
| 363 |
+
"\n",
|
| 364 |
+
"processed_datasets = dataset.map(\n",
|
| 365 |
+
" preprocess_function,\n",
|
| 366 |
+
" batched=True,\n",
|
| 367 |
+
" num_proc=1,\n",
|
| 368 |
+
" remove_columns=dataset[\"train\"].column_names,\n",
|
| 369 |
+
" load_from_cache_file=False,\n",
|
| 370 |
+
" desc=\"Running tokenizer on dataset\",\n",
|
| 371 |
+
")\n",
|
| 372 |
+
"\n",
|
| 373 |
+
"train_dataset = processed_datasets[\"train\"]\n",
|
| 374 |
+
"eval_dataset = processed_datasets[\"validation\"]\n",
|
| 375 |
+
"\n",
|
| 376 |
+
"train_dataloader = DataLoader(\n",
|
| 377 |
+
" train_dataset, shuffle=True, collate_fn=default_data_collator, batch_size=batch_size, pin_memory=True\n",
|
| 378 |
+
")\n",
|
| 379 |
+
"eval_dataloader = DataLoader(eval_dataset, collate_fn=default_data_collator, batch_size=batch_size, pin_memory=True)"
|
| 380 |
+
]
|
| 381 |
+
},
|
| 382 |
+
{
|
| 383 |
+
"cell_type": "code",
|
| 384 |
+
"execution_count": 5,
|
| 385 |
+
"id": "f733a3c6",
|
| 386 |
+
"metadata": {
|
| 387 |
+
"ExecuteTime": {
|
| 388 |
+
"end_time": "2023-05-30T08:38:22.907922Z",
|
| 389 |
+
"start_time": "2023-05-30T08:38:22.901057Z"
|
| 390 |
+
}
|
| 391 |
+
},
|
| 392 |
+
"outputs": [],
|
| 393 |
+
"source": [
|
| 394 |
+
"# optimizer and lr scheduler\n",
|
| 395 |
+
"optimizer = torch.optim.AdamW(model.parameters(), lr=lr)\n",
|
| 396 |
+
"lr_scheduler = get_linear_schedule_with_warmup(\n",
|
| 397 |
+
" optimizer=optimizer,\n",
|
| 398 |
+
" num_warmup_steps=0,\n",
|
| 399 |
+
" num_training_steps=(len(train_dataloader) * num_epochs),\n",
|
| 400 |
+
")"
|
| 401 |
+
]
|
| 402 |
+
},
|
| 403 |
+
{
|
| 404 |
+
"cell_type": "code",
|
| 405 |
+
"execution_count": null,
|
| 406 |
+
"id": "6b3a4090",
|
| 407 |
+
"metadata": {
|
| 408 |
+
"ExecuteTime": {
|
| 409 |
+
"end_time": "2023-05-30T08:42:29.409070Z",
|
| 410 |
+
"start_time": "2023-05-30T08:38:50.102263Z"
|
| 411 |
+
}
|
| 412 |
+
},
|
| 413 |
+
"outputs": [],
|
| 414 |
+
"source": [
|
| 415 |
+
"# training and evaluation\n",
|
| 416 |
+
"model = model.to(device)\n",
|
| 417 |
+
"\n",
|
| 418 |
+
"for epoch in range(num_epochs):\n",
|
| 419 |
+
" model.train()\n",
|
| 420 |
+
" total_loss = 0\n",
|
| 421 |
+
" for step, batch in enumerate(tqdm(train_dataloader)):\n",
|
| 422 |
+
" batch = {k: v.to(device) for k, v in batch.items()}\n",
|
| 423 |
+
" outputs = model(**batch)\n",
|
| 424 |
+
" loss = outputs.loss\n",
|
| 425 |
+
" total_loss += loss.detach().float()\n",
|
| 426 |
+
" loss.backward()\n",
|
| 427 |
+
" optimizer.step()\n",
|
| 428 |
+
" lr_scheduler.step()\n",
|
| 429 |
+
" optimizer.zero_grad()\n",
|
| 430 |
+
"\n",
|
| 431 |
+
" model.eval()\n",
|
| 432 |
+
" eval_loss = 0\n",
|
| 433 |
+
" eval_preds = []\n",
|
| 434 |
+
" for step, batch in enumerate(tqdm(eval_dataloader)):\n",
|
| 435 |
+
" batch = {k: v.to(device) for k, v in batch.items()}\n",
|
| 436 |
+
" with torch.no_grad():\n",
|
| 437 |
+
" outputs = model(**batch)\n",
|
| 438 |
+
" loss = outputs.loss\n",
|
| 439 |
+
" eval_loss += loss.detach().float()\n",
|
| 440 |
+
" eval_preds.extend(\n",
|
| 441 |
+
" tokenizer.batch_decode(torch.argmax(outputs.logits, -1).detach().cpu().numpy(), skip_special_tokens=True)\n",
|
| 442 |
+
" )\n",
|
| 443 |
+
"\n",
|
| 444 |
+
" eval_epoch_loss = eval_loss / len(eval_dataloader)\n",
|
| 445 |
+
" eval_ppl = torch.exp(eval_epoch_loss)\n",
|
| 446 |
+
" train_epoch_loss = total_loss / len(train_dataloader)\n",
|
| 447 |
+
" train_ppl = torch.exp(train_epoch_loss)\n",
|
| 448 |
+
" print(f\"{epoch=}: {train_ppl=} {train_epoch_loss=} {eval_ppl=} {eval_epoch_loss=}\")"
|
| 449 |
+
]
|
| 450 |
+
},
|
| 451 |
+
{
|
| 452 |
+
"cell_type": "code",
|
| 453 |
+
"execution_count": 8,
|
| 454 |
+
"id": "6cafa67b",
|
| 455 |
+
"metadata": {
|
| 456 |
+
"ExecuteTime": {
|
| 457 |
+
"end_time": "2023-05-30T08:42:42.844671Z",
|
| 458 |
+
"start_time": "2023-05-30T08:42:42.840447Z"
|
| 459 |
+
}
|
| 460 |
+
},
|
| 461 |
+
"outputs": [
|
| 462 |
+
{
|
| 463 |
+
"name": "stdout",
|
| 464 |
+
"output_type": "stream",
|
| 465 |
+
"text": [
|
| 466 |
+
"accuracy=85.46255506607929 % on the evaluation dataset\n",
|
| 467 |
+
"eval_preds[:10]=['neutral', 'neutral', 'neutral', 'neutral', 'neutral', 'positive', 'neutral', 'negative', 'neutral', 'positive']\n",
|
| 468 |
+
"dataset['validation']['text_label'][:10]=['neutral', 'neutral', 'neutral', 'neutral', 'neutral', 'positive', 'neutral', 'negative', 'positive', 'neutral']\n"
|
| 469 |
+
]
|
| 470 |
+
}
|
| 471 |
+
],
|
| 472 |
+
"source": [
|
| 473 |
+
"# print accuracy\n",
|
| 474 |
+
"correct = 0\n",
|
| 475 |
+
"total = 0\n",
|
| 476 |
+
"for pred, true in zip(eval_preds, dataset[\"validation\"][\"text_label\"]):\n",
|
| 477 |
+
" if pred.strip() == true.strip():\n",
|
| 478 |
+
" correct += 1\n",
|
| 479 |
+
" total += 1\n",
|
| 480 |
+
"accuracy = correct / total * 100\n",
|
| 481 |
+
"print(f\"{accuracy=} % on the evaluation dataset\")\n",
|
| 482 |
+
"print(f\"{eval_preds[:10]=}\")\n",
|
| 483 |
+
"print(f\"{dataset['validation']['text_label'][:10]=}\")"
|
| 484 |
+
]
|
| 485 |
+
},
|
| 486 |
+
{
|
| 487 |
+
"cell_type": "code",
|
| 488 |
+
"execution_count": 9,
|
| 489 |
+
"id": "a8de6005",
|
| 490 |
+
"metadata": {
|
| 491 |
+
"ExecuteTime": {
|
| 492 |
+
"end_time": "2023-05-30T08:42:45.752765Z",
|
| 493 |
+
"start_time": "2023-05-30T08:42:45.742397Z"
|
| 494 |
+
}
|
| 495 |
+
},
|
| 496 |
+
"outputs": [],
|
| 497 |
+
"source": [
|
| 498 |
+
"# saving model\n",
|
| 499 |
+
"peft_model_id = f\"{model_name_or_path}_{peft_config.peft_type}_{peft_config.task_type}\"\n",
|
| 500 |
+
"model.save_pretrained(peft_model_id)"
|
| 501 |
+
]
|
| 502 |
+
},
|
| 503 |
+
{
|
| 504 |
+
"cell_type": "code",
|
| 505 |
+
"execution_count": null,
|
| 506 |
+
"id": "bd20cd4c",
|
| 507 |
+
"metadata": {
|
| 508 |
+
"ExecuteTime": {
|
| 509 |
+
"end_time": "2023-05-30T08:42:47.660873Z",
|
| 510 |
+
"start_time": "2023-05-30T08:42:47.488293Z"
|
| 511 |
+
}
|
| 512 |
+
},
|
| 513 |
+
"outputs": [
|
| 514 |
+
{
|
| 515 |
+
"name": "stdout",
|
| 516 |
+
"output_type": "stream",
|
| 517 |
+
"text": [
|
| 518 |
+
"164K\tt5-large_PROMPT_TUNING_SEQ_2_SEQ_LM/adapter_model.safetensors\r\n"
|
| 519 |
+
]
|
| 520 |
+
}
|
| 521 |
+
],
|
| 522 |
+
"source": [
|
| 523 |
+
"ckpt = f\"{peft_model_id}/adapter_model.safetensors\"\n",
|
| 524 |
+
"!du -h $ckpt"
|
| 525 |
+
]
|
| 526 |
+
},
|
| 527 |
+
{
|
| 528 |
+
"cell_type": "code",
|
| 529 |
+
"execution_count": 11,
|
| 530 |
+
"id": "76c2fc29",
|
| 531 |
+
"metadata": {
|
| 532 |
+
"ExecuteTime": {
|
| 533 |
+
"end_time": "2023-05-30T08:42:56.721990Z",
|
| 534 |
+
"start_time": "2023-05-30T08:42:49.060700Z"
|
| 535 |
+
}
|
| 536 |
+
},
|
| 537 |
+
"outputs": [],
|
| 538 |
+
"source": [
|
| 539 |
+
"from peft import PeftModel, PeftConfig\n",
|
| 540 |
+
"\n",
|
| 541 |
+
"peft_model_id = f\"{model_name_or_path}_{peft_config.peft_type}_{peft_config.task_type}\"\n",
|
| 542 |
+
"\n",
|
| 543 |
+
"config = PeftConfig.from_pretrained(peft_model_id)\n",
|
| 544 |
+
"model = AutoModelForSeq2SeqLM.from_pretrained(config.base_model_name_or_path)\n",
|
| 545 |
+
"model = PeftModel.from_pretrained(model, peft_model_id)"
|
| 546 |
+
]
|
| 547 |
+
},
|
| 548 |
+
{
|
| 549 |
+
"cell_type": "code",
|
| 550 |
+
"execution_count": 12,
|
| 551 |
+
"id": "d997f1cc",
|
| 552 |
+
"metadata": {
|
| 553 |
+
"ExecuteTime": {
|
| 554 |
+
"end_time": "2023-05-30T08:42:59.600916Z",
|
| 555 |
+
"start_time": "2023-05-30T08:42:58.961468Z"
|
| 556 |
+
}
|
| 557 |
+
},
|
| 558 |
+
"outputs": [
|
| 559 |
+
{
|
| 560 |
+
"name": "stdout",
|
| 561 |
+
"output_type": "stream",
|
| 562 |
+
"text": [
|
| 563 |
+
"Danske Bank is Denmark 's largest bank with 3.5 million customers .\n",
|
| 564 |
+
"tensor([[ 3039, 1050, 1925, 19, 18001, 3, 31, 7, 2015, 2137,\n",
|
| 565 |
+
" 28, 3, 9285, 770, 722, 3, 5, 1]])\n",
|
| 566 |
+
"tensor([[ 0, 7163, 1]])\n",
|
| 567 |
+
"['neutral']\n"
|
| 568 |
+
]
|
| 569 |
+
}
|
| 570 |
+
],
|
| 571 |
+
"source": [
|
| 572 |
+
"model.eval()\n",
|
| 573 |
+
"i = 107\n",
|
| 574 |
+
"input_ids = tokenizer(dataset[\"validation\"][text_column][i], return_tensors=\"pt\").input_ids\n",
|
| 575 |
+
"print(dataset[\"validation\"][text_column][i])\n",
|
| 576 |
+
"print(input_ids)\n",
|
| 577 |
+
"\n",
|
| 578 |
+
"with torch.no_grad():\n",
|
| 579 |
+
" outputs = model.generate(input_ids=input_ids, max_new_tokens=10)\n",
|
| 580 |
+
" print(outputs)\n",
|
| 581 |
+
" print(tokenizer.batch_decode(outputs.detach().cpu().numpy(), skip_special_tokens=True))"
|
| 582 |
+
]
|
| 583 |
+
}
|
| 584 |
+
],
|
| 585 |
+
"metadata": {
|
| 586 |
+
"kernelspec": {
|
| 587 |
+
"display_name": "Python 3 (ipykernel)",
|
| 588 |
+
"language": "python",
|
| 589 |
+
"name": "python3"
|
| 590 |
+
},
|
| 591 |
+
"language_info": {
|
| 592 |
+
"codemirror_mode": {
|
| 593 |
+
"name": "ipython",
|
| 594 |
+
"version": 3
|
| 595 |
+
},
|
| 596 |
+
"file_extension": ".py",
|
| 597 |
+
"mimetype": "text/x-python",
|
| 598 |
+
"name": "python",
|
| 599 |
+
"nbconvert_exporter": "python",
|
| 600 |
+
"pygments_lexer": "ipython3",
|
| 601 |
+
"version": "3.11.13"
|
| 602 |
+
},
|
| 603 |
+
"toc": {
|
| 604 |
+
"base_numbering": 1,
|
| 605 |
+
"nav_menu": {},
|
| 606 |
+
"number_sections": true,
|
| 607 |
+
"sideBar": true,
|
| 608 |
+
"skip_h1_title": false,
|
| 609 |
+
"title_cell": "Table of Contents",
|
| 610 |
+
"title_sidebar": "Contents",
|
| 611 |
+
"toc_cell": false,
|
| 612 |
+
"toc_position": {},
|
| 613 |
+
"toc_section_display": true,
|
| 614 |
+
"toc_window_display": false
|
| 615 |
+
},
|
| 616 |
+
"varInspector": {
|
| 617 |
+
"cols": {
|
| 618 |
+
"lenName": 16,
|
| 619 |
+
"lenType": 16,
|
| 620 |
+
"lenVar": 40
|
| 621 |
+
},
|
| 622 |
+
"kernels_config": {
|
| 623 |
+
"python": {
|
| 624 |
+
"delete_cmd_postfix": "",
|
| 625 |
+
"delete_cmd_prefix": "del ",
|
| 626 |
+
"library": "var_list.py",
|
| 627 |
+
"varRefreshCmd": "print(var_dic_list())"
|
| 628 |
+
},
|
| 629 |
+
"r": {
|
| 630 |
+
"delete_cmd_postfix": ") ",
|
| 631 |
+
"delete_cmd_prefix": "rm(",
|
| 632 |
+
"library": "var_list.r",
|
| 633 |
+
"varRefreshCmd": "cat(var_dic_list()) "
|
| 634 |
+
}
|
| 635 |
+
},
|
| 636 |
+
"types_to_exclude": [
|
| 637 |
+
"module",
|
| 638 |
+
"function",
|
| 639 |
+
"builtin_function_or_method",
|
| 640 |
+
"instance",
|
| 641 |
+
"_Feature"
|
| 642 |
+
],
|
| 643 |
+
"window_display": false
|
| 644 |
+
},
|
| 645 |
+
"vscode": {
|
| 646 |
+
"interpreter": {
|
| 647 |
+
"hash": "aee8b7b246df8f9039afb4144a1f6fd8d2ca17a180786b69acc140d282b71a49"
|
| 648 |
+
}
|
| 649 |
+
}
|
| 650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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "5f93b7d1",
|
| 7 |
+
"metadata": {
|
| 8 |
+
"ExecuteTime": {
|
| 9 |
+
"end_time": "2023-05-30T09:49:56.334329Z",
|
| 10 |
+
"start_time": "2023-05-30T09:49:54.494916Z"
|
| 11 |
+
}
|
| 12 |
+
},
|
| 13 |
+
"outputs": [],
|
| 14 |
+
"source": [
|
| 15 |
+
"import os\n",
|
| 16 |
+
"\n",
|
| 17 |
+
"import torch\n",
|
| 18 |
+
"from transformers import (\n",
|
| 19 |
+
" AutoTokenizer,\n",
|
| 20 |
+
" default_data_collator,\n",
|
| 21 |
+
" AutoModelForSeq2SeqLM,\n",
|
| 22 |
+
" Seq2SeqTrainingArguments,\n",
|
| 23 |
+
" Seq2SeqTrainer,\n",
|
| 24 |
+
" GenerationConfig,\n",
|
| 25 |
+
")\n",
|
| 26 |
+
"from peft import get_peft_model, PromptTuningInit, PromptTuningConfig, TaskType\n",
|
| 27 |
+
"from datasets import load_dataset\n",
|
| 28 |
+
"\n",
|
| 29 |
+
"os.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\"\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"device = torch.accelerator.current_accelerator().type if hasattr(torch, \"accelerator\") else \"cuda\"\n",
|
| 32 |
+
"model_name_or_path = \"t5-large\"\n",
|
| 33 |
+
"tokenizer_name_or_path = \"t5-large\"\n",
|
| 34 |
+
"\n",
|
| 35 |
+
"checkpoint_name = \"financial_sentiment_analysis_prefix_tuning_v1.pt\"\n",
|
| 36 |
+
"text_column = \"sentence\"\n",
|
| 37 |
+
"label_column = \"text_label\"\n",
|
| 38 |
+
"max_length = 8\n",
|
| 39 |
+
"lr = 1e0\n",
|
| 40 |
+
"num_epochs = 5\n",
|
| 41 |
+
"batch_size = 8"
|
| 42 |
+
]
|
| 43 |
+
},
|
| 44 |
+
{
|
| 45 |
+
"cell_type": "code",
|
| 46 |
+
"execution_count": 2,
|
| 47 |
+
"id": "8d0850ac",
|
| 48 |
+
"metadata": {
|
| 49 |
+
"ExecuteTime": {
|
| 50 |
+
"end_time": "2023-05-30T09:50:04.808527Z",
|
| 51 |
+
"start_time": "2023-05-30T09:49:56.953075Z"
|
| 52 |
+
}
|
| 53 |
+
},
|
| 54 |
+
"outputs": [
|
| 55 |
+
{
|
| 56 |
+
"name": "stdout",
|
| 57 |
+
"output_type": "stream",
|
| 58 |
+
"text": [
|
| 59 |
+
"trainable params: 40,960 || all params: 737,709,056 || trainable%: 0.0056\n"
|
| 60 |
+
]
|
| 61 |
+
},
|
| 62 |
+
{
|
| 63 |
+
"data": {
|
| 64 |
+
"text/plain": [
|
| 65 |
+
"PeftModelForSeq2SeqLM(\n",
|
| 66 |
+
" (base_model): T5ForConditionalGeneration(\n",
|
| 67 |
+
" (shared): Embedding(32128, 1024)\n",
|
| 68 |
+
" (encoder): T5Stack(\n",
|
| 69 |
+
" (embed_tokens): Embedding(32128, 1024)\n",
|
| 70 |
+
" (block): ModuleList(\n",
|
| 71 |
+
" (0): T5Block(\n",
|
| 72 |
+
" (layer): ModuleList(\n",
|
| 73 |
+
" (0): T5LayerSelfAttention(\n",
|
| 74 |
+
" (SelfAttention): T5Attention(\n",
|
| 75 |
+
" (q): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 76 |
+
" (k): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 77 |
+
" (v): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 78 |
+
" (o): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 79 |
+
" (relative_attention_bias): Embedding(32, 16)\n",
|
| 80 |
+
" )\n",
|
| 81 |
+
" (layer_norm): T5LayerNorm()\n",
|
| 82 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
| 83 |
+
" )\n",
|
| 84 |
+
" (1): T5LayerFF(\n",
|
| 85 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
| 86 |
+
" (wi): Linear(in_features=1024, out_features=4096, bias=False)\n",
|
| 87 |
+
" (wo): Linear(in_features=4096, out_features=1024, bias=False)\n",
|
| 88 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
| 89 |
+
" (act): ReLU()\n",
|
| 90 |
+
" )\n",
|
| 91 |
+
" (layer_norm): T5LayerNorm()\n",
|
| 92 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
| 93 |
+
" )\n",
|
| 94 |
+
" )\n",
|
| 95 |
+
" )\n",
|
| 96 |
+
" (1-23): 23 x T5Block(\n",
|
| 97 |
+
" (layer): ModuleList(\n",
|
| 98 |
+
" (0): T5LayerSelfAttention(\n",
|
| 99 |
+
" (SelfAttention): T5Attention(\n",
|
| 100 |
+
" (q): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 101 |
+
" (k): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 102 |
+
" (v): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 103 |
+
" (o): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 104 |
+
" )\n",
|
| 105 |
+
" (layer_norm): T5LayerNorm()\n",
|
| 106 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
| 107 |
+
" )\n",
|
| 108 |
+
" (1): T5LayerFF(\n",
|
| 109 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
| 110 |
+
" (wi): Linear(in_features=1024, out_features=4096, bias=False)\n",
|
| 111 |
+
" (wo): Linear(in_features=4096, out_features=1024, bias=False)\n",
|
| 112 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
| 113 |
+
" (act): ReLU()\n",
|
| 114 |
+
" )\n",
|
| 115 |
+
" (layer_norm): T5LayerNorm()\n",
|
| 116 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
| 117 |
+
" )\n",
|
| 118 |
+
" )\n",
|
| 119 |
+
" )\n",
|
| 120 |
+
" )\n",
|
| 121 |
+
" (final_layer_norm): T5LayerNorm()\n",
|
| 122 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
| 123 |
+
" )\n",
|
| 124 |
+
" (decoder): T5Stack(\n",
|
| 125 |
+
" (embed_tokens): Embedding(32128, 1024)\n",
|
| 126 |
+
" (block): ModuleList(\n",
|
| 127 |
+
" (0): T5Block(\n",
|
| 128 |
+
" (layer): ModuleList(\n",
|
| 129 |
+
" (0): T5LayerSelfAttention(\n",
|
| 130 |
+
" (SelfAttention): T5Attention(\n",
|
| 131 |
+
" (q): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 132 |
+
" (k): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 133 |
+
" (v): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 134 |
+
" (o): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 135 |
+
" (relative_attention_bias): Embedding(32, 16)\n",
|
| 136 |
+
" )\n",
|
| 137 |
+
" (layer_norm): T5LayerNorm()\n",
|
| 138 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
| 139 |
+
" )\n",
|
| 140 |
+
" (1): T5LayerCrossAttention(\n",
|
| 141 |
+
" (EncDecAttention): T5Attention(\n",
|
| 142 |
+
" (q): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 143 |
+
" (k): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 144 |
+
" (v): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 145 |
+
" (o): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 146 |
+
" )\n",
|
| 147 |
+
" (layer_norm): T5LayerNorm()\n",
|
| 148 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
| 149 |
+
" )\n",
|
| 150 |
+
" (2): T5LayerFF(\n",
|
| 151 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
| 152 |
+
" (wi): Linear(in_features=1024, out_features=4096, bias=False)\n",
|
| 153 |
+
" (wo): Linear(in_features=4096, out_features=1024, bias=False)\n",
|
| 154 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
| 155 |
+
" (act): ReLU()\n",
|
| 156 |
+
" )\n",
|
| 157 |
+
" (layer_norm): T5LayerNorm()\n",
|
| 158 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
| 159 |
+
" )\n",
|
| 160 |
+
" )\n",
|
| 161 |
+
" )\n",
|
| 162 |
+
" (1-23): 23 x T5Block(\n",
|
| 163 |
+
" (layer): ModuleList(\n",
|
| 164 |
+
" (0): T5LayerSelfAttention(\n",
|
| 165 |
+
" (SelfAttention): T5Attention(\n",
|
| 166 |
+
" (q): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 167 |
+
" (k): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 168 |
+
" (v): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 169 |
+
" (o): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 170 |
+
" )\n",
|
| 171 |
+
" (layer_norm): T5LayerNorm()\n",
|
| 172 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
| 173 |
+
" )\n",
|
| 174 |
+
" (1): T5LayerCrossAttention(\n",
|
| 175 |
+
" (EncDecAttention): T5Attention(\n",
|
| 176 |
+
" (q): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 177 |
+
" (k): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 178 |
+
" (v): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 179 |
+
" (o): Linear(in_features=1024, out_features=1024, bias=False)\n",
|
| 180 |
+
" )\n",
|
| 181 |
+
" (layer_norm): T5LayerNorm()\n",
|
| 182 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
| 183 |
+
" )\n",
|
| 184 |
+
" (2): T5LayerFF(\n",
|
| 185 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
| 186 |
+
" (wi): Linear(in_features=1024, out_features=4096, bias=False)\n",
|
| 187 |
+
" (wo): Linear(in_features=4096, out_features=1024, bias=False)\n",
|
| 188 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
| 189 |
+
" (act): ReLU()\n",
|
| 190 |
+
" )\n",
|
| 191 |
+
" (layer_norm): T5LayerNorm()\n",
|
| 192 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
| 193 |
+
" )\n",
|
| 194 |
+
" )\n",
|
| 195 |
+
" )\n",
|
| 196 |
+
" )\n",
|
| 197 |
+
" (final_layer_norm): T5LayerNorm()\n",
|
| 198 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
| 199 |
+
" )\n",
|
| 200 |
+
" (lm_head): Linear(in_features=1024, out_features=32128, bias=False)\n",
|
| 201 |
+
" )\n",
|
| 202 |
+
" (prompt_encoder): ModuleDict(\n",
|
| 203 |
+
" (default): PromptEmbedding(\n",
|
| 204 |
+
" (embedding): Embedding(40, 1024)\n",
|
| 205 |
+
" )\n",
|
| 206 |
+
" )\n",
|
| 207 |
+
" (word_embeddings): Embedding(32128, 1024)\n",
|
| 208 |
+
")"
|
| 209 |
+
]
|
| 210 |
+
},
|
| 211 |
+
"execution_count": 2,
|
| 212 |
+
"metadata": {},
|
| 213 |
+
"output_type": "execute_result"
|
| 214 |
+
}
|
| 215 |
+
],
|
| 216 |
+
"source": [
|
| 217 |
+
"# creating model\n",
|
| 218 |
+
"peft_config = peft_config = PromptTuningConfig(\n",
|
| 219 |
+
" task_type=TaskType.SEQ_2_SEQ_LM,\n",
|
| 220 |
+
" prompt_tuning_init=PromptTuningInit.TEXT,\n",
|
| 221 |
+
" num_virtual_tokens=20,\n",
|
| 222 |
+
" prompt_tuning_init_text=\"What is the sentiment of this article?\\n\",\n",
|
| 223 |
+
" inference_mode=False,\n",
|
| 224 |
+
" tokenizer_name_or_path=model_name_or_path,\n",
|
| 225 |
+
")\n",
|
| 226 |
+
"\n",
|
| 227 |
+
"model = AutoModelForSeq2SeqLM.from_pretrained(model_name_or_path)\n",
|
| 228 |
+
"model = get_peft_model(model, peft_config)\n",
|
| 229 |
+
"model.print_trainable_parameters()\n",
|
| 230 |
+
"model"
|
| 231 |
+
]
|
| 232 |
+
},
|
| 233 |
+
{
|
| 234 |
+
"cell_type": "code",
|
| 235 |
+
"execution_count": 3,
|
| 236 |
+
"id": "4ee2babf",
|
| 237 |
+
"metadata": {
|
| 238 |
+
"ExecuteTime": {
|
| 239 |
+
"end_time": "2023-05-30T09:50:09.224782Z",
|
| 240 |
+
"start_time": "2023-05-30T09:50:08.172611Z"
|
| 241 |
+
}
|
| 242 |
+
},
|
| 243 |
+
"outputs": [
|
| 244 |
+
{
|
| 245 |
+
"name": "stderr",
|
| 246 |
+
"output_type": "stream",
|
| 247 |
+
"text": [
|
| 248 |
+
"Using the latest cached version of the dataset since financial_phrasebank couldn't be found on the Hugging Face Hub\n",
|
| 249 |
+
"Found the latest cached dataset configuration 'sentences_allagree' at /root/.cache/huggingface/datasets/financial_phrasebank/sentences_allagree/1.0.0/550bde12e6c30e2674da973a55f57edde5181d53f5a5a34c1531c53f93b7e141 (last modified on Thu Jul 31 06:43:45 2025).\n"
|
| 250 |
+
]
|
| 251 |
+
},
|
| 252 |
+
{
|
| 253 |
+
"data": {
|
| 254 |
+
"application/vnd.jupyter.widget-view+json": {
|
| 255 |
+
"model_id": "79ef90cbad2f4c2088f01102cadb8a3b",
|
| 256 |
+
"version_major": 2,
|
| 257 |
+
"version_minor": 0
|
| 258 |
+
},
|
| 259 |
+
"text/plain": [
|
| 260 |
+
"Map: 0%| | 0/2037 [00:00<?, ? examples/s]"
|
| 261 |
+
]
|
| 262 |
+
},
|
| 263 |
+
"metadata": {},
|
| 264 |
+
"output_type": "display_data"
|
| 265 |
+
},
|
| 266 |
+
{
|
| 267 |
+
"data": {
|
| 268 |
+
"application/vnd.jupyter.widget-view+json": {
|
| 269 |
+
"model_id": "0f5b177b658646cfa90b3a2801138807",
|
| 270 |
+
"version_major": 2,
|
| 271 |
+
"version_minor": 0
|
| 272 |
+
},
|
| 273 |
+
"text/plain": [
|
| 274 |
+
"Map: 0%| | 0/227 [00:00<?, ? examples/s]"
|
| 275 |
+
]
|
| 276 |
+
},
|
| 277 |
+
"metadata": {},
|
| 278 |
+
"output_type": "display_data"
|
| 279 |
+
},
|
| 280 |
+
{
|
| 281 |
+
"data": {
|
| 282 |
+
"text/plain": [
|
| 283 |
+
"{'sentence': 'This new partnership agreement represents a significant milestone for both parties .',\n",
|
| 284 |
+
" 'label': 2,\n",
|
| 285 |
+
" 'text_label': 'positive'}"
|
| 286 |
+
]
|
| 287 |
+
},
|
| 288 |
+
"execution_count": 3,
|
| 289 |
+
"metadata": {},
|
| 290 |
+
"output_type": "execute_result"
|
| 291 |
+
}
|
| 292 |
+
],
|
| 293 |
+
"source": [
|
| 294 |
+
"# loading dataset\n",
|
| 295 |
+
"dataset = load_dataset(\"financial_phrasebank\", \"sentences_allagree\")\n",
|
| 296 |
+
"dataset = dataset[\"train\"].train_test_split(test_size=0.1)\n",
|
| 297 |
+
"dataset[\"validation\"] = dataset[\"test\"]\n",
|
| 298 |
+
"del dataset[\"test\"]\n",
|
| 299 |
+
"\n",
|
| 300 |
+
"classes = dataset[\"train\"].features[\"label\"].names\n",
|
| 301 |
+
"dataset = dataset.map(\n",
|
| 302 |
+
" lambda x: {\"text_label\": [classes[label] for label in x[\"label\"]]},\n",
|
| 303 |
+
" batched=True,\n",
|
| 304 |
+
" num_proc=1,\n",
|
| 305 |
+
")\n",
|
| 306 |
+
"\n",
|
| 307 |
+
"dataset[\"train\"][0]"
|
| 308 |
+
]
|
| 309 |
+
},
|
| 310 |
+
{
|
| 311 |
+
"cell_type": "code",
|
| 312 |
+
"execution_count": 4,
|
| 313 |
+
"id": "adf9608c",
|
| 314 |
+
"metadata": {
|
| 315 |
+
"ExecuteTime": {
|
| 316 |
+
"end_time": "2023-05-30T09:50:12.176663Z",
|
| 317 |
+
"start_time": "2023-05-30T09:50:11.421273Z"
|
| 318 |
+
}
|
| 319 |
+
},
|
| 320 |
+
"outputs": [
|
| 321 |
+
{
|
| 322 |
+
"data": {
|
| 323 |
+
"application/vnd.jupyter.widget-view+json": {
|
| 324 |
+
"model_id": "0a5f7b5967704fab97f11bc07813625c",
|
| 325 |
+
"version_major": 2,
|
| 326 |
+
"version_minor": 0
|
| 327 |
+
},
|
| 328 |
+
"text/plain": [
|
| 329 |
+
"Running tokenizer on dataset: 0%| | 0/2037 [00:00<?, ? examples/s]"
|
| 330 |
+
]
|
| 331 |
+
},
|
| 332 |
+
"metadata": {},
|
| 333 |
+
"output_type": "display_data"
|
| 334 |
+
},
|
| 335 |
+
{
|
| 336 |
+
"data": {
|
| 337 |
+
"application/vnd.jupyter.widget-view+json": {
|
| 338 |
+
"model_id": "1ff9578c074e4736a8812f6ffc8138b5",
|
| 339 |
+
"version_major": 2,
|
| 340 |
+
"version_minor": 0
|
| 341 |
+
},
|
| 342 |
+
"text/plain": [
|
| 343 |
+
"Running tokenizer on dataset: 0%| | 0/227 [00:00<?, ? examples/s]"
|
| 344 |
+
]
|
| 345 |
+
},
|
| 346 |
+
"metadata": {},
|
| 347 |
+
"output_type": "display_data"
|
| 348 |
+
}
|
| 349 |
+
],
|
| 350 |
+
"source": [
|
| 351 |
+
"# data preprocessing\n",
|
| 352 |
+
"tokenizer = AutoTokenizer.from_pretrained(model_name_or_path)\n",
|
| 353 |
+
"\n",
|
| 354 |
+
"\n",
|
| 355 |
+
"def preprocess_function(examples):\n",
|
| 356 |
+
" inputs = examples[text_column]\n",
|
| 357 |
+
" targets = examples[label_column]\n",
|
| 358 |
+
" model_inputs = tokenizer(inputs, max_length=max_length, padding=\"max_length\", truncation=True, return_tensors=\"pt\")\n",
|
| 359 |
+
" labels = tokenizer(targets, max_length=2, padding=\"max_length\", truncation=True, return_tensors=\"pt\")\n",
|
| 360 |
+
" labels = labels[\"input_ids\"]\n",
|
| 361 |
+
" labels[labels == tokenizer.pad_token_id] = -100\n",
|
| 362 |
+
" model_inputs[\"labels\"] = labels\n",
|
| 363 |
+
" return model_inputs\n",
|
| 364 |
+
"\n",
|
| 365 |
+
"\n",
|
| 366 |
+
"processed_datasets = dataset.map(\n",
|
| 367 |
+
" preprocess_function,\n",
|
| 368 |
+
" batched=True,\n",
|
| 369 |
+
" num_proc=1,\n",
|
| 370 |
+
" remove_columns=dataset[\"train\"].column_names,\n",
|
| 371 |
+
" load_from_cache_file=False,\n",
|
| 372 |
+
" desc=\"Running tokenizer on dataset\",\n",
|
| 373 |
+
")\n",
|
| 374 |
+
"\n",
|
| 375 |
+
"train_dataset = processed_datasets[\"train\"].shuffle()\n",
|
| 376 |
+
"eval_dataset = processed_datasets[\"validation\"]"
|
| 377 |
+
]
|
| 378 |
+
},
|
| 379 |
+
{
|
| 380 |
+
"cell_type": "code",
|
| 381 |
+
"execution_count": 5,
|
| 382 |
+
"id": "6b3a4090",
|
| 383 |
+
"metadata": {
|
| 384 |
+
"ExecuteTime": {
|
| 385 |
+
"end_time": "2023-05-30T09:53:10.336984Z",
|
| 386 |
+
"start_time": "2023-05-30T09:50:14.780995Z"
|
| 387 |
+
}
|
| 388 |
+
},
|
| 389 |
+
"outputs": [
|
| 390 |
+
{
|
| 391 |
+
"name": "stderr",
|
| 392 |
+
"output_type": "stream",
|
| 393 |
+
"text": [
|
| 394 |
+
"[W731 07:06:51.135038656 OperatorEntry.cpp:217] Warning: Warning only once for all operators, other operators may also be overridden.\n",
|
| 395 |
+
" Overriding a previously registered kernel for the same operator and the same dispatch key\n",
|
| 396 |
+
" operator: aten::geometric_(Tensor(a!) self, float p, *, Generator? generator=None) -> Tensor(a!)\n",
|
| 397 |
+
" registered at /pytorch/build/aten/src/ATen/RegisterSchema.cpp:6\n",
|
| 398 |
+
" dispatch key: XPU\n",
|
| 399 |
+
" previous kernel: registered at /pytorch/aten/src/ATen/VmapModeRegistrations.cpp:37\n",
|
| 400 |
+
" new kernel: registered at /build/intel-pytorch-extension/build/Release/csrc/gpu/csrc/gpu/xpu/ATen/RegisterXPU_0.cpp:172 (function operator())\n"
|
| 401 |
+
]
|
| 402 |
+
},
|
| 403 |
+
{
|
| 404 |
+
"name": "stdout",
|
| 405 |
+
"output_type": "stream",
|
| 406 |
+
"text": [
|
| 407 |
+
"[2025-07-31 07:06:51,984] [INFO] [real_accelerator.py:254:get_accelerator] Setting ds_accelerator to xpu (auto detect)\n"
|
| 408 |
+
]
|
| 409 |
+
},
|
| 410 |
+
{
|
| 411 |
+
"name": "stderr",
|
| 412 |
+
"output_type": "stream",
|
| 413 |
+
"text": [
|
| 414 |
+
"/usr/bin/ld: cannot find -laio: No such file or directory\n",
|
| 415 |
+
"collect2: error: ld returned 1 exit status\n"
|
| 416 |
+
]
|
| 417 |
+
},
|
| 418 |
+
{
|
| 419 |
+
"name": "stdout",
|
| 420 |
+
"output_type": "stream",
|
| 421 |
+
"text": [
|
| 422 |
+
"[2025-07-31 07:06:52,955] [INFO] [logging.py:107:log_dist] [Rank -1] [TorchCheckpointEngine] Initialized with serialization = False\n"
|
| 423 |
+
]
|
| 424 |
+
},
|
| 425 |
+
{
|
| 426 |
+
"name": "stderr",
|
| 427 |
+
"output_type": "stream",
|
| 428 |
+
"text": [
|
| 429 |
+
"No label_names provided for model class `PeftModelForSeq2SeqLM`. Since `PeftModel` hides base models input arguments, if label_names is not given, label_names can't be set automatically within `Trainer`. Note that empty label_names list will be used instead.\n"
|
| 430 |
+
]
|
| 431 |
+
},
|
| 432 |
+
{
|
| 433 |
+
"data": {
|
| 434 |
+
"text/html": [
|
| 435 |
+
"\n",
|
| 436 |
+
" <div>\n",
|
| 437 |
+
" \n",
|
| 438 |
+
" <progress value='1275' max='1275' style='width:300px; height:20px; vertical-align: middle;'></progress>\n",
|
| 439 |
+
" [1275/1275 03:31, Epoch 5/5]\n",
|
| 440 |
+
" </div>\n",
|
| 441 |
+
" <table border=\"1\" class=\"dataframe\">\n",
|
| 442 |
+
" <thead>\n",
|
| 443 |
+
" <tr style=\"text-align: left;\">\n",
|
| 444 |
+
" <th>Epoch</th>\n",
|
| 445 |
+
" <th>Training Loss</th>\n",
|
| 446 |
+
" <th>Validation Loss</th>\n",
|
| 447 |
+
" <th>Accuracy</th>\n",
|
| 448 |
+
" </tr>\n",
|
| 449 |
+
" </thead>\n",
|
| 450 |
+
" <tbody>\n",
|
| 451 |
+
" <tr>\n",
|
| 452 |
+
" <td>1</td>\n",
|
| 453 |
+
" <td>2.169900</td>\n",
|
| 454 |
+
" <td>0.507156</td>\n",
|
| 455 |
+
" <td>0.621145</td>\n",
|
| 456 |
+
" </tr>\n",
|
| 457 |
+
" <tr>\n",
|
| 458 |
+
" <td>2</td>\n",
|
| 459 |
+
" <td>0.537700</td>\n",
|
| 460 |
+
" <td>0.430996</td>\n",
|
| 461 |
+
" <td>0.651982</td>\n",
|
| 462 |
+
" </tr>\n",
|
| 463 |
+
" <tr>\n",
|
| 464 |
+
" <td>3</td>\n",
|
| 465 |
+
" <td>0.482200</td>\n",
|
| 466 |
+
" <td>0.426718</td>\n",
|
| 467 |
+
" <td>0.696035</td>\n",
|
| 468 |
+
" </tr>\n",
|
| 469 |
+
" <tr>\n",
|
| 470 |
+
" <td>4</td>\n",
|
| 471 |
+
" <td>0.459700</td>\n",
|
| 472 |
+
" <td>0.470894</td>\n",
|
| 473 |
+
" <td>0.682819</td>\n",
|
| 474 |
+
" </tr>\n",
|
| 475 |
+
" <tr>\n",
|
| 476 |
+
" <td>5</td>\n",
|
| 477 |
+
" <td>0.436000</td>\n",
|
| 478 |
+
" <td>0.409604</td>\n",
|
| 479 |
+
" <td>0.718062</td>\n",
|
| 480 |
+
" </tr>\n",
|
| 481 |
+
" </tbody>\n",
|
| 482 |
+
"</table><p>"
|
| 483 |
+
],
|
| 484 |
+
"text/plain": [
|
| 485 |
+
"<IPython.core.display.HTML object>"
|
| 486 |
+
]
|
| 487 |
+
},
|
| 488 |
+
"metadata": {},
|
| 489 |
+
"output_type": "display_data"
|
| 490 |
+
},
|
| 491 |
+
{
|
| 492 |
+
"data": {
|
| 493 |
+
"text/plain": [
|
| 494 |
+
"TrainOutput(global_step=1275, training_loss=0.8170911183076747, metrics={'train_runtime': 213.5513, 'train_samples_per_second': 47.693, 'train_steps_per_second': 5.97, 'total_flos': 344546979840000.0, 'train_loss': 0.8170911183076747, 'epoch': 5.0})"
|
| 495 |
+
]
|
| 496 |
+
},
|
| 497 |
+
"execution_count": 5,
|
| 498 |
+
"metadata": {},
|
| 499 |
+
"output_type": "execute_result"
|
| 500 |
+
}
|
| 501 |
+
],
|
| 502 |
+
"source": [
|
| 503 |
+
"# training and evaluation\n",
|
| 504 |
+
"\n",
|
| 505 |
+
"\n",
|
| 506 |
+
"def compute_metrics(eval_preds):\n",
|
| 507 |
+
" preds, labels = eval_preds\n",
|
| 508 |
+
" preds = tokenizer.batch_decode(preds, skip_special_tokens=True)\n",
|
| 509 |
+
" labels = tokenizer.batch_decode(labels, skip_special_tokens=True)\n",
|
| 510 |
+
"\n",
|
| 511 |
+
" correct = 0\n",
|
| 512 |
+
" total = 0\n",
|
| 513 |
+
" for pred, true in zip(preds, labels):\n",
|
| 514 |
+
" if pred.strip() == true.strip():\n",
|
| 515 |
+
" correct += 1\n",
|
| 516 |
+
" total += 1\n",
|
| 517 |
+
" accuracy = correct / total\n",
|
| 518 |
+
" return {\"accuracy\": accuracy}\n",
|
| 519 |
+
"\n",
|
| 520 |
+
"\n",
|
| 521 |
+
"training_args = Seq2SeqTrainingArguments(\n",
|
| 522 |
+
" \"out\",\n",
|
| 523 |
+
" per_device_train_batch_size=batch_size,\n",
|
| 524 |
+
" learning_rate=lr,\n",
|
| 525 |
+
" num_train_epochs=num_epochs,\n",
|
| 526 |
+
" eval_strategy=\"epoch\",\n",
|
| 527 |
+
" logging_strategy=\"epoch\",\n",
|
| 528 |
+
" save_strategy=\"no\",\n",
|
| 529 |
+
" report_to=[],\n",
|
| 530 |
+
" predict_with_generate=True,\n",
|
| 531 |
+
" generation_config=GenerationConfig(max_length=max_length),\n",
|
| 532 |
+
")\n",
|
| 533 |
+
"trainer = Seq2SeqTrainer(\n",
|
| 534 |
+
" model=model,\n",
|
| 535 |
+
" processing_class=tokenizer,\n",
|
| 536 |
+
" args=training_args,\n",
|
| 537 |
+
" train_dataset=train_dataset,\n",
|
| 538 |
+
" eval_dataset=eval_dataset,\n",
|
| 539 |
+
" data_collator=default_data_collator,\n",
|
| 540 |
+
" compute_metrics=compute_metrics,\n",
|
| 541 |
+
")\n",
|
| 542 |
+
"trainer.train()"
|
| 543 |
+
]
|
| 544 |
+
},
|
| 545 |
+
{
|
| 546 |
+
"cell_type": "code",
|
| 547 |
+
"execution_count": 6,
|
| 548 |
+
"id": "a8de6005",
|
| 549 |
+
"metadata": {
|
| 550 |
+
"ExecuteTime": {
|
| 551 |
+
"end_time": "2023-05-30T09:53:13.045146Z",
|
| 552 |
+
"start_time": "2023-05-30T09:53:13.035612Z"
|
| 553 |
+
}
|
| 554 |
+
},
|
| 555 |
+
"outputs": [],
|
| 556 |
+
"source": [
|
| 557 |
+
"# saving model\n",
|
| 558 |
+
"peft_model_id = f\"{model_name_or_path}_{peft_config.peft_type}_{peft_config.task_type}\"\n",
|
| 559 |
+
"model.save_pretrained(peft_model_id)"
|
| 560 |
+
]
|
| 561 |
+
},
|
| 562 |
+
{
|
| 563 |
+
"cell_type": "code",
|
| 564 |
+
"execution_count": null,
|
| 565 |
+
"id": "bd20cd4c",
|
| 566 |
+
"metadata": {
|
| 567 |
+
"ExecuteTime": {
|
| 568 |
+
"end_time": "2023-05-30T09:53:15.240763Z",
|
| 569 |
+
"start_time": "2023-05-30T09:53:15.059304Z"
|
| 570 |
+
}
|
| 571 |
+
},
|
| 572 |
+
"outputs": [],
|
| 573 |
+
"source": [
|
| 574 |
+
"ckpt = f\"{peft_model_id}/adapter_model.safetensors\"\n",
|
| 575 |
+
"!du -h $ckpt"
|
| 576 |
+
]
|
| 577 |
+
},
|
| 578 |
+
{
|
| 579 |
+
"cell_type": "code",
|
| 580 |
+
"execution_count": 8,
|
| 581 |
+
"id": "76c2fc29",
|
| 582 |
+
"metadata": {
|
| 583 |
+
"ExecuteTime": {
|
| 584 |
+
"end_time": "2023-05-30T09:53:25.055105Z",
|
| 585 |
+
"start_time": "2023-05-30T09:53:17.797989Z"
|
| 586 |
+
}
|
| 587 |
+
},
|
| 588 |
+
"outputs": [],
|
| 589 |
+
"source": [
|
| 590 |
+
"from peft import PeftModel, PeftConfig\n",
|
| 591 |
+
"\n",
|
| 592 |
+
"peft_model_id = f\"{model_name_or_path}_{peft_config.peft_type}_{peft_config.task_type}\"\n",
|
| 593 |
+
"\n",
|
| 594 |
+
"config = PeftConfig.from_pretrained(peft_model_id)\n",
|
| 595 |
+
"model = AutoModelForSeq2SeqLM.from_pretrained(config.base_model_name_or_path)\n",
|
| 596 |
+
"model = PeftModel.from_pretrained(model, peft_model_id)"
|
| 597 |
+
]
|
| 598 |
+
},
|
| 599 |
+
{
|
| 600 |
+
"cell_type": "code",
|
| 601 |
+
"execution_count": 9,
|
| 602 |
+
"id": "d997f1cc",
|
| 603 |
+
"metadata": {
|
| 604 |
+
"ExecuteTime": {
|
| 605 |
+
"end_time": "2023-05-30T09:53:26.777030Z",
|
| 606 |
+
"start_time": "2023-05-30T09:53:26.013697Z"
|
| 607 |
+
}
|
| 608 |
+
},
|
| 609 |
+
"outputs": [
|
| 610 |
+
{
|
| 611 |
+
"name": "stdout",
|
| 612 |
+
"output_type": "stream",
|
| 613 |
+
"text": [
|
| 614 |
+
"EPS grew to 0.04 eur from 0.02 eur .\n",
|
| 615 |
+
"{'input_ids': tensor([[ 3, 24935, 3, 4774, 12, 4097, 6348, 3, 1238, 45,\n",
|
| 616 |
+
" 4097, 4305, 3, 1238, 3, 5, 1]]), 'attention_mask': tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])}\n",
|
| 617 |
+
"tensor([[ 0, 1465, 1]])\n",
|
| 618 |
+
"['positive']\n"
|
| 619 |
+
]
|
| 620 |
+
}
|
| 621 |
+
],
|
| 622 |
+
"source": [
|
| 623 |
+
"model.eval()\n",
|
| 624 |
+
"i = 107\n",
|
| 625 |
+
"inputs = tokenizer(dataset[\"validation\"][text_column][i], return_tensors=\"pt\")\n",
|
| 626 |
+
"print(dataset[\"validation\"][text_column][i])\n",
|
| 627 |
+
"print(inputs)\n",
|
| 628 |
+
"\n",
|
| 629 |
+
"with torch.no_grad():\n",
|
| 630 |
+
" outputs = model.generate(input_ids=inputs[\"input_ids\"], max_new_tokens=10)\n",
|
| 631 |
+
" print(outputs)\n",
|
| 632 |
+
" print(tokenizer.batch_decode(outputs.detach().cpu().numpy(), skip_special_tokens=True))"
|
| 633 |
+
]
|
| 634 |
+
},
|
| 635 |
+
{
|
| 636 |
+
"cell_type": "code",
|
| 637 |
+
"execution_count": null,
|
| 638 |
+
"id": "fb746c1e",
|
| 639 |
+
"metadata": {},
|
| 640 |
+
"outputs": [],
|
| 641 |
+
"source": []
|
| 642 |
+
}
|
| 643 |
+
],
|
| 644 |
+
"metadata": {
|
| 645 |
+
"kernelspec": {
|
| 646 |
+
"display_name": "Python 3 (ipykernel)",
|
| 647 |
+
"language": "python",
|
| 648 |
+
"name": "python3"
|
| 649 |
+
},
|
| 650 |
+
"language_info": {
|
| 651 |
+
"codemirror_mode": {
|
| 652 |
+
"name": "ipython",
|
| 653 |
+
"version": 3
|
| 654 |
+
},
|
| 655 |
+
"file_extension": ".py",
|
| 656 |
+
"mimetype": "text/x-python",
|
| 657 |
+
"name": "python",
|
| 658 |
+
"nbconvert_exporter": "python",
|
| 659 |
+
"pygments_lexer": "ipython3",
|
| 660 |
+
"version": "3.11.13"
|
| 661 |
+
},
|
| 662 |
+
"toc": {
|
| 663 |
+
"base_numbering": 1,
|
| 664 |
+
"nav_menu": {},
|
| 665 |
+
"number_sections": true,
|
| 666 |
+
"sideBar": true,
|
| 667 |
+
"skip_h1_title": false,
|
| 668 |
+
"title_cell": "Table of Contents",
|
| 669 |
+
"title_sidebar": "Contents",
|
| 670 |
+
"toc_cell": false,
|
| 671 |
+
"toc_position": {},
|
| 672 |
+
"toc_section_display": true,
|
| 673 |
+
"toc_window_display": false
|
| 674 |
+
},
|
| 675 |
+
"varInspector": {
|
| 676 |
+
"cols": {
|
| 677 |
+
"lenName": 16,
|
| 678 |
+
"lenType": 16,
|
| 679 |
+
"lenVar": 40
|
| 680 |
+
},
|
| 681 |
+
"kernels_config": {
|
| 682 |
+
"python": {
|
| 683 |
+
"delete_cmd_postfix": "",
|
| 684 |
+
"delete_cmd_prefix": "del ",
|
| 685 |
+
"library": "var_list.py",
|
| 686 |
+
"varRefreshCmd": "print(var_dic_list())"
|
| 687 |
+
},
|
| 688 |
+
"r": {
|
| 689 |
+
"delete_cmd_postfix": ") ",
|
| 690 |
+
"delete_cmd_prefix": "rm(",
|
| 691 |
+
"library": "var_list.r",
|
| 692 |
+
"varRefreshCmd": "cat(var_dic_list()) "
|
| 693 |
+
}
|
| 694 |
+
},
|
| 695 |
+
"types_to_exclude": [
|
| 696 |
+
"module",
|
| 697 |
+
"function",
|
| 698 |
+
"builtin_function_or_method",
|
| 699 |
+
"instance",
|
| 700 |
+
"_Feature"
|
| 701 |
+
],
|
| 702 |
+
"window_display": false
|
| 703 |
+
},
|
| 704 |
+
"vscode": {
|
| 705 |
+
"interpreter": {
|
| 706 |
+
"hash": "aee8b7b246df8f9039afb4144a1f6fd8d2ca17a180786b69acc140d282b71a49"
|
| 707 |
+
}
|
| 708 |
+
}
|
| 709 |
+
},
|
| 710 |
+
"nbformat": 4,
|
| 711 |
+
"nbformat_minor": 5
|
| 712 |
+
}
|
tasks/tasksmith-ecb1931929df/tests/source/examples/conditional_generation/requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
transformers
|
| 2 |
+
accelerate
|
| 3 |
+
evaluate
|
| 4 |
+
deepspeed
|
| 5 |
+
tqdm
|
| 6 |
+
datasets
|
| 7 |
+
safetensors
|
| 8 |
+
scikit-learn
|
tasks/tasksmith-ecb1931929df/tests/source/examples/corda_finetuning/README.md
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 |
+
|
| 5 |
+
|
| 6 |
+
Existing PEFT methods are mostly agnostic of the context of a task of concern, e.g., a downstream task to learn or some pre-trained world knowledge to maintain.
|
| 7 |
+
[CorDA](https://openreview.net/pdf?id=Gi00NVru6n) builds task-aware LoRA adapters from weight decomposition oriented by the context of the task concerned.
|
| 8 |
+
|
| 9 |
+
Concretely, CorDA randomly collects a few (by default 256 in our `preprocess.py`) data samples from a target task, e.g. questions from a QA dataset or instructions to write a code or solve a math problem, and feeds these samples into a pre-trained LLM. We can obtain the covariance matrix of the input activation of each linear layer, i.e., $C=XX^T\in\mathcal{R}^{d_{in}\times d_{in}}$.
|
| 10 |
+
We then perform singular value decomposition (SVD) for the weight $W\in \mathcal{R}^{d_{out}\times d_{in}}$ multiplied by the covariance matrix, i.e., $\verb|SVD|(WC) = U\Sigma V^T$. In this way, the context expressed by these representative covariance matrices is able to orientate the decomposition, such that the principal components (the singular vectors with the largest singular values) are most associated with the task of concern (please refer to Fig.2 of our paper for the advantage of our decomposition over the plain SVD). To ensure the same inference result with the pre-trained model at the start of adaptation, we multiply the inverse of these covariance matrices with the decomposed components, i.e., $\hat{W}=U\Sigma V^T C^{-1}$.
|
| 11 |
+
|
| 12 |
+
Thanks to the task-awareness, you can choose how to utilize the task-specific principal components. For examples, if you want to adapt a model to a new task without losing the knowledge of a question-answering dataset, e.g., TriviaQA and NQopen, you can sample questions from this dataset to collect covariance matrices, and keep the principal components frozen because they compact the ability of this dataset, while using the lowest components with the smallest $r$ singular values to initialize the learnable LoRA adapters. This is achieved by the **knowledge-preserved mode (KPM)** of CorDA, which learns new tasks effectively while keeping the world knowledge you are concerned about as sound as possible. Alternatively, when your primary objective is to maximize performance on the finetuning task, disregarding the preservation of world knowledge, the **instruction-previewed mode (IPM**) will be favored. In this mode, CorDA uses the instruction and response from the fine-tuning task (e.g., Math or Code) to produce the covariance matrices. The principal components with the largest $r$ singular values, capturing the characteristics of the finetuning task in advance, can better adapt to the new ability, so they are used to initialize the LoRA adapters, with the remaining components frozen. IPM can further accelerate convergence to enhance the fine-tuning performance on downstream tasks.
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
The implementations of KPM and IPM are compared as follows:
|
| 16 |
+
|
| 17 |
+
| Mode | Collect covariance from | LoRA $A$ | LoRA $B$ |
|
| 18 |
+
|---|---|---|---
|
| 19 |
+
|KPM | questions from the knowledge benchmark to maintain | $A=\sqrt{\Sigma}\_{[-r:]}(V^T C^{-1})\_{[-r:,:]}$ | $B=U_{[:,-r:]}\sqrt{\Sigma}_{[-r:]}$ |
|
| 20 |
+
IPM | instructions and responses from the downstream task to learn | $A= \sqrt{\Sigma}\_{[:r]} (V^T C^{-1})\_{[:r,:]}$ | $B =U_{[:,:r]} \sqrt{\Sigma}_{[:r]}$ |
|
| 21 |
+
|
| 22 |
+
### Comparison with alternative methods
|
| 23 |
+
|
| 24 |
+
The distinction between CorDA with other similar LoRA initialization methods is summarized as follows:
|
| 25 |
+
|
| 26 |
+
| Method | Initialization for | SVD on | Data-driven | Supports knowledge maintenance |
|
| 27 |
+
| - | - | - | - | - |
|
| 28 |
+
| PiSSA | $A$ and $B$ | weights | no | no |
|
| 29 |
+
| EVA | $A$ | activations | yes | no |
|
| 30 |
+
|CorDA | $A$ and $B$ | weights (oriented by covariance) | yes | yes |
|
| 31 |
+
|
| 32 |
+
"Supports knowledge maintenance" denotes the ability of explicitly associating a knowledge benchmark with some components of the pre-trained weights after decomposition, and keeping these components frozen during fine-tuning.
|
| 33 |
+
|
| 34 |
+
### Some Results
|
| 35 |
+
|
| 36 |
+
- Performance with knowledge-preserved mode (sample from NQopen, fine-tune on Math)
|
| 37 |
+
|
| 38 |
+
| Method | Model | NQ open | GSM8k | Math | Avg. |
|
| 39 |
+
|---|---|---|---|---|---|
|
| 40 |
+
|Pre-trained|Llama-2-7b| 14.99 | -| - | - |
|
| 41 |
+
|LoRA|Llama-2-7b|1.27| 42.68 | 5.88 | 16.61 |
|
| 42 |
+
|**CorDA (KPM)** |Llama-2-7b| **8.20** | **46.32** | **7.00** | **20.51** |
|
| 43 |
+
|Pre-trained|Llama-2-13b|23.63|-|-|-|
|
| 44 |
+
|LoRA|Llama-2-13b| 16.26 | 57.24 | 8.92 | 27.47 |
|
| 45 |
+
|**CorDA (KPM)** |Llama-2-13b| **19.86** | **59.29** | **9.62** | **29.59** |
|
| 46 |
+
|Pre-trained|Llama-3-8b|13.41|-|-|-|
|
| 47 |
+
|LoRA|Llama-3-8b| 8.75 | 72.33 | 24.04| 35.04 |
|
| 48 |
+
|**CorDA (KPM)** |Llama-3-8b| **9.61** | **74.68** | **25.34** | **36.54** |
|
| 49 |
+
|Pre-trained|Gemma-2-9b|12.85|-|-|-|
|
| 50 |
+
|LoRA|Gemma-2-9b| 9.28 | 83.47 | 42.30| 45.02 |
|
| 51 |
+
|**CorDA (KPM)** |Gemma-2-9b|**10.17** | **84.08** | **42.64** | **45.63** |
|
| 52 |
+
|
| 53 |
+
- Performance with instruction-previewed mode (sample from Math, fine-tune on Math)
|
| 54 |
+
|
| 55 |
+
| Method | Model | GSM8k | Math |
|
| 56 |
+
| --- | --- | --- | ---|
|
| 57 |
+
|LoRA| Llama-2-7b | 42.68 | 5.88 |
|
| 58 |
+
|PiSSA | Llama-2-7b | 51.63 | 7.32 |
|
| 59 |
+
| **CorDA (IPM)** | Llama-2-7b | **53.45** | **8.64** |
|
| 60 |
+
|LoRA| Llama-2-13b | 57.24 | 8.92 |
|
| 61 |
+
|PiSSA | Llama-2-13b |60.88 | 11.08|
|
| 62 |
+
| **CorDA (IPM)** | Llama-2-13b | **62.47** |**11.54** |
|
| 63 |
+
|LoRA| Gemma-2-9b | 83.47 | 42.30 |
|
| 64 |
+
|PiSSA | Gemma-2-9b | 84.23 | 43.52|
|
| 65 |
+
| **CorDA (IPM)** | Gemma-2-9b | **84.45** | **43.88** |
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
## Quick Start
|
| 69 |
+
|
| 70 |
+
### Knowledge-preserved adaptation mode
|
| 71 |
+
|
| 72 |
+
```py
|
| 73 |
+
import torch
|
| 74 |
+
from peft import LoraConfig, get_peft_model
|
| 75 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 76 |
+
from peft.tuners.lora.config import CordaConfig
|
| 77 |
+
from peft.tuners.lora.corda import preprocess_corda
|
| 78 |
+
from trl import SFTConfig, SFTTrainer
|
| 79 |
+
from datasets import load_dataset
|
| 80 |
+
|
| 81 |
+
model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf", dtype=torch.bfloat16, device_map="auto")
|
| 82 |
+
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
|
| 83 |
+
tokenizer.pad_token_id = tokenizer.eos_token_id
|
| 84 |
+
sampled_dataset = load_dataset("wikitext", "wikitext-2-raw-v1", split="train[:256]")
|
| 85 |
+
dataset = load_dataset("imdb", split="train[:256]")
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def run_model():
|
| 89 |
+
for batch in sampled_dataset:
|
| 90 |
+
input_ids = batch["text"]
|
| 91 |
+
input_ids = input_ids.to(model.device)
|
| 92 |
+
with torch.no_grad():
|
| 93 |
+
model(input_ids)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
corda_config = CordaConfig(
|
| 97 |
+
corda_method="kpm",
|
| 98 |
+
)
|
| 99 |
+
lora_config = LoraConfig(
|
| 100 |
+
init_lora_weights="corda",
|
| 101 |
+
corda_config=corda_config,
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
# Call `preprocess_corda` first to collect covariance matrix and build SVD result for model
|
| 105 |
+
# For more details, please refer to documentation of `preprocess_corda`
|
| 106 |
+
preprocess_corda(model, lora_config, run_model=run_model)
|
| 107 |
+
|
| 108 |
+
# Call `get_peft_model` after preprocessing, or else you'll encounter error
|
| 109 |
+
peft_model = get_peft_model(model, lora_config)
|
| 110 |
+
peft_model.print_trainable_parameters()
|
| 111 |
+
|
| 112 |
+
training_args = SFTConfig(dataset_text_field="text", max_length=128)
|
| 113 |
+
trainer = SFTTrainer(
|
| 114 |
+
model=peft_model,
|
| 115 |
+
args=training_args,
|
| 116 |
+
train_dataset=dataset,
|
| 117 |
+
processing_class=tokenizer,
|
| 118 |
+
)
|
| 119 |
+
trainer.train()
|
| 120 |
+
peft_model.save_pretrained("corda-llama-2-7b")
|
| 121 |
+
```
|
| 122 |
+
|
| 123 |
+
### Instruction-previewed adaptation mode
|
| 124 |
+
|
| 125 |
+
```py
|
| 126 |
+
# Get model and dataset identically as KPM...
|
| 127 |
+
|
| 128 |
+
# Different from KPM, we run the model on dataset of the downstream task to collect covariance matrices
|
| 129 |
+
def run_model():
|
| 130 |
+
for batch in dataset:
|
| 131 |
+
input_ids = batch["text"]
|
| 132 |
+
input_ids = input_ids.to(model.device)
|
| 133 |
+
with torch.no_grad():
|
| 134 |
+
model(input_ids)
|
| 135 |
+
|
| 136 |
+
# Different from KPM, we set `corda_method` to `"ipm"`
|
| 137 |
+
corda_config = CordaConfig(
|
| 138 |
+
corda_method="ipm",
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
# The rest of training process is identical to KPM...
|
| 142 |
+
```
|
| 143 |
+
|
| 144 |
+
## Advanced Usage
|
| 145 |
+
|
| 146 |
+
### Preprocessing
|
| 147 |
+
|
| 148 |
+
`preprocess.py`: This script builds CorDA adapters for a model, and saves the adapters initial weights and residual model weights to a specified directory. Example usage:
|
| 149 |
+
|
| 150 |
+
#### Knowledge-preserved adaptation mode
|
| 151 |
+
|
| 152 |
+
```bash
|
| 153 |
+
export CUDA_VISIBLE_DEVICES=0 # force to use device 0 of CUDA GPU
|
| 154 |
+
export ZE_AFFINITY_MASK=0 # force to use device 0 of Intel XPU
|
| 155 |
+
|
| 156 |
+
python -u preprocess.py --model_id="meta-llama/Llama-2-7b-hf" \
|
| 157 |
+
--r 128 --seed 233 \
|
| 158 |
+
--save_model --save_path {path_to_residual_model} \
|
| 159 |
+
--calib_dataset "nqopen"
|
| 160 |
+
```
|
| 161 |
+
Arguments:
|
| 162 |
+
|
| 163 |
+
- `--model_id` is the pre-trained model for decomposition.
|
| 164 |
+
- `--r` is the low rank of LoRA, e.g. 128.
|
| 165 |
+
- `--calib_dataset` specifies the dataset to sample data to obtain covariance matrices. KPA mode uses QA datasets such as `"nqopen"`, `"traivia_qa"`, or other choices.
|
| 166 |
+
- `--save_model` saves the initialized model in `--save_path`.
|
| 167 |
+
|
| 168 |
+
#### Instruction-previewed adaptation mode
|
| 169 |
+
|
| 170 |
+
```bash
|
| 171 |
+
export CUDA_VISIBLE_DEVICES=0 # force to use device 0 of CUDA GPU
|
| 172 |
+
export ZE_AFFINITY_MASK=0 # force to use device 0 of Intel XPU
|
| 173 |
+
|
| 174 |
+
python -u preprocess.py --model_id="meta-llama/Llama-2-7b-hf" \
|
| 175 |
+
--r 128 --seed 233 \
|
| 176 |
+
--save_model --save_path {path_to_residual_model} \
|
| 177 |
+
--first_eigen --calib_dataset "MetaMATH"
|
| 178 |
+
```
|
| 179 |
+
|
| 180 |
+
Arguments:
|
| 181 |
+
|
| 182 |
+
- `--first_eigen` uses the largest $r$ singular values and vectors to initialize the learnable adapter for the instruction-previewed adaptation mode.
|
| 183 |
+
- `--calib_dataset` specifies the dataset to sample data to obtain covariance matrices. Instruction-previewed mode uses the downstream task dataset you are learning, such as `"MetaMATH"`, `"codefeedback"`, `"WizLMinstruct"`, `"alpaca"`, or other choices.
|
| 184 |
+
|
| 185 |
+
#### Note about memory consumption
|
| 186 |
+
|
| 187 |
+
The process of collecting covariance matrices is performed in `torch.float32` by default. If you would like to reduce the memory consumption of preprocessing, you can specify `use_float16_for_covariance=True` in `CordaConfig` to collect covariance matrices in `torch.float16`. But this may cause numerical instability only in a few cases, such that the initialized model does not ensure the exact same inference result as the original model. So it is suggested to check, e.g., comparing the inference result of Wiki/PTB perplexity before and after preprocessing, if you choose to perform in `torch.float16`.
|
| 188 |
+
|
| 189 |
+
### Fine-tuning
|
| 190 |
+
|
| 191 |
+
`corda_finetuning.py`: This script fine-tunes the preprocessed model built above on a downstream task.
|
| 192 |
+
|
| 193 |
+
Example usage:
|
| 194 |
+
|
| 195 |
+
```bash
|
| 196 |
+
python corda_finetuning.py \
|
| 197 |
+
--model_name_or_path {path_to_residual_model} \
|
| 198 |
+
--output_dir {path_to_output_model} \
|
| 199 |
+
--corda_mode True \
|
| 200 |
+
--data_path meta-math/MetaMathQA \
|
| 201 |
+
--dataset_split "train[:100000]" \
|
| 202 |
+
--dataset_field query response \
|
| 203 |
+
--num_train_epochs 1 \
|
| 204 |
+
--per_device_train_batch_size 1 \
|
| 205 |
+
--gradient_accumulation_steps 32 \
|
| 206 |
+
--save_strategy "steps" \
|
| 207 |
+
--save_steps 100 \
|
| 208 |
+
--save_total_limit 1 \
|
| 209 |
+
--learning_rate 2e-5 \
|
| 210 |
+
--weight_decay 0. \
|
| 211 |
+
--warmup_ratio 0.03 \
|
| 212 |
+
--lr_scheduler_type "cosine" \
|
| 213 |
+
--logging_steps 1 \
|
| 214 |
+
--bf16 True \
|
| 215 |
+
--tf32 True \
|
| 216 |
+
--report_to none
|
| 217 |
+
```
|
| 218 |
+
|
| 219 |
+
### Convert CorDA to LoRA
|
| 220 |
+
|
| 221 |
+
The main advantage of CorDA is concentrated during the training phase. For a trained CorDA adapter, we recommend converting it equivalently to the LoRA adapter for using and sharing.
|
| 222 |
+
|
| 223 |
+
```python
|
| 224 |
+
# The fine-tuned matrices $A$ and $B$ in CorDA adapter is saved and should be combined with the residual model.
|
| 225 |
+
peft_model.save_pretrained(output_dir)
|
| 226 |
+
# Given the matrices $A_0$ and $B_0$, initialized by CorDA and untrained, and the trained matrices $A$ and $B$,
|
| 227 |
+
# 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'$.
|
| 228 |
+
peft_model.save_pretrained(output_dir, path_initial_model_for_weight_conversion="corda_init")
|
| 229 |
+
```
|
| 230 |
+
|
| 231 |
+
This conversion enables the loading of LoRA on top of a standard base model:
|
| 232 |
+
|
| 233 |
+
```python
|
| 234 |
+
import torch
|
| 235 |
+
from peft import PeftModel
|
| 236 |
+
from transformers import AutoModelForCausalLM
|
| 237 |
+
|
| 238 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 239 |
+
"meta-llama/Llama-2-7b-hf", dtype=torch.bfloat16, device_map="auto"
|
| 240 |
+
)
|
| 241 |
+
# No SVD is performed during this step, and the base model remains unaltered.
|
| 242 |
+
peft_model = PeftModel.from_pretrained(model, "corda-llama-2-7b-lora")
|
| 243 |
+
```
|
| 244 |
+
|
| 245 |
+
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.
|
| 246 |
+
|
| 247 |
+
Note that this conversion is not supported if `rslora` is used in combination with `rank_pattern` or `alpha_pattern`.
|
| 248 |
+
|
| 249 |
+
## Citation
|
| 250 |
+
```
|
| 251 |
+
@inproceedings{yangcorda,
|
| 252 |
+
title={CorDA: Context-Oriented Decomposition Adaptation of Large Language Models for Task-Aware Parameter-Efficient Fine-tuning},
|
| 253 |
+
author={Yang, Yibo and Li, Xiaojie and Zhou, Zhongzhu and Song, Shuaiwen Leon and Wu, Jianlong and Nie, Liqiang and Ghanem, Bernard},
|
| 254 |
+
booktitle={The Thirty-eighth Annual Conference on Neural Information Processing Systems},
|
| 255 |
+
year={2024},
|
| 256 |
+
}
|
| 257 |
+
```
|
tasks/tasksmith-ecb1931929df/tests/source/examples/corda_finetuning/corda_finetuning.py
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
import copy
|
| 16 |
+
import os
|
| 17 |
+
from collections.abc import Sequence
|
| 18 |
+
from dataclasses import dataclass, field
|
| 19 |
+
from typing import Optional
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
import transformers
|
| 23 |
+
from datasets import load_dataset
|
| 24 |
+
from transformers import Trainer
|
| 25 |
+
|
| 26 |
+
from peft import LoraConfig, PeftModel, get_peft_model
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
IGNORE_INDEX = -100
|
| 30 |
+
|
| 31 |
+
PROMPT = (
|
| 32 |
+
"Below is an instruction that describes a task. "
|
| 33 |
+
"Write a response that appropriately completes the request.\n\n"
|
| 34 |
+
"### Instruction:\n{instruction}\n\n### Response:"
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def get_nb_trainable_parameters(model) -> tuple[int, int]:
|
| 39 |
+
r"""
|
| 40 |
+
Returns the number of trainable parameters and the number of all parameters in the model.
|
| 41 |
+
"""
|
| 42 |
+
trainable_params = 0
|
| 43 |
+
all_param = 0
|
| 44 |
+
for _, param in model.named_parameters():
|
| 45 |
+
num_params = param.numel()
|
| 46 |
+
# if using DS Zero 3 and the weights are initialized empty
|
| 47 |
+
if num_params == 0 and hasattr(param, "ds_numel"):
|
| 48 |
+
num_params = param.ds_numel
|
| 49 |
+
|
| 50 |
+
# Due to the design of 4bit linear layers from bitsandbytes
|
| 51 |
+
# one needs to multiply the number of parameters by 2 to get
|
| 52 |
+
# the correct number of parameters
|
| 53 |
+
if param.__class__.__name__ == "Params4bit":
|
| 54 |
+
num_bytes = param.quant_storage.itemsize if hasattr(param, "quant_storage") else 1
|
| 55 |
+
num_params = num_params * 2 * num_bytes
|
| 56 |
+
|
| 57 |
+
all_param += num_params
|
| 58 |
+
if param.requires_grad:
|
| 59 |
+
trainable_params += num_params
|
| 60 |
+
|
| 61 |
+
return trainable_params, all_param
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
@dataclass
|
| 65 |
+
class TrainingArguments(transformers.TrainingArguments):
|
| 66 |
+
model_name_or_path: Optional[str] = field(default="facebook/opt-125m")
|
| 67 |
+
data_path: str = field(default=None, metadata={"help": "Path to the training data."})
|
| 68 |
+
dataset_split: str = field(default="train[:100000]", metadata={"help": "(`['train', 'test', 'eval']`):"})
|
| 69 |
+
dataset_field: list[str] = field(default=None, metadata={"help": "Fields of dataset input and output."})
|
| 70 |
+
dataloader_num_proc: int = field(default=16, metadata={"help": "Number of processes to load dataset"})
|
| 71 |
+
dataloader_batch_size: int = field(
|
| 72 |
+
default=3000,
|
| 73 |
+
metadata={
|
| 74 |
+
"help": "batch size to load dataset. To set the batch size for training, you should pass --batch_size argument instead."
|
| 75 |
+
},
|
| 76 |
+
)
|
| 77 |
+
optim: str = field(default="adamw_torch")
|
| 78 |
+
model_max_length: int = field(
|
| 79 |
+
default=512,
|
| 80 |
+
metadata={"help": "Maximum sequence length. Sequences will be right padded (and possibly truncated)."},
|
| 81 |
+
)
|
| 82 |
+
lora_r: int = field(
|
| 83 |
+
default=None,
|
| 84 |
+
metadata={"help": "The rank of LoRA adapter. When passing `None`, CorDA or full fine-tuning is used."},
|
| 85 |
+
)
|
| 86 |
+
corda_mode: bool = field(default=True, metadata={"help": "True for CorDA mode"})
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def safe_save_model_for_hf_trainer(trainer: transformers.Trainer, output_dir: str):
|
| 90 |
+
"""Collects the state dict and dump to disk."""
|
| 91 |
+
state_dict = trainer.model.state_dict()
|
| 92 |
+
if trainer.args.should_save:
|
| 93 |
+
cpu_state_dict = {key: value.cpu() for key, value in state_dict.items()}
|
| 94 |
+
del state_dict
|
| 95 |
+
trainer._save(output_dir, state_dict=cpu_state_dict) # noqa
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def smart_tokenizer_and_embedding_resize(
|
| 99 |
+
special_tokens_dict: dict,
|
| 100 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
| 101 |
+
model: transformers.PreTrainedModel,
|
| 102 |
+
):
|
| 103 |
+
"""Resize tokenizer and embedding.
|
| 104 |
+
|
| 105 |
+
Note: This is the unoptimized version that may make your embedding size not be divisible by 64.
|
| 106 |
+
"""
|
| 107 |
+
num_new_tokens = tokenizer.add_special_tokens(special_tokens_dict)
|
| 108 |
+
model.resize_token_embeddings(len(tokenizer))
|
| 109 |
+
|
| 110 |
+
if num_new_tokens > 0:
|
| 111 |
+
input_embeddings = model.get_input_embeddings().weight.data
|
| 112 |
+
output_embeddings = model.get_output_embeddings().weight.data
|
| 113 |
+
|
| 114 |
+
input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
|
| 115 |
+
output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
|
| 116 |
+
|
| 117 |
+
input_embeddings[-num_new_tokens:] = input_embeddings_avg
|
| 118 |
+
output_embeddings[-num_new_tokens:] = output_embeddings_avg
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def _tokenize_fn(strings: Sequence[str], tokenizer: transformers.PreTrainedTokenizer) -> dict:
|
| 122 |
+
"""Tokenize a list of strings."""
|
| 123 |
+
tokenized_list = [
|
| 124 |
+
tokenizer(
|
| 125 |
+
text,
|
| 126 |
+
return_tensors="pt",
|
| 127 |
+
padding="longest",
|
| 128 |
+
max_length=tokenizer.model_max_length,
|
| 129 |
+
truncation=True,
|
| 130 |
+
)
|
| 131 |
+
for text in strings
|
| 132 |
+
]
|
| 133 |
+
input_ids = labels = [tokenized.input_ids[0] for tokenized in tokenized_list]
|
| 134 |
+
input_ids_lens = labels_lens = [
|
| 135 |
+
tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item() for tokenized in tokenized_list
|
| 136 |
+
]
|
| 137 |
+
return {
|
| 138 |
+
"input_ids": input_ids,
|
| 139 |
+
"labels": labels,
|
| 140 |
+
"input_ids_lens": input_ids_lens,
|
| 141 |
+
"labels_lens": labels_lens,
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def preprocess(
|
| 146 |
+
sources: Sequence[str],
|
| 147 |
+
targets: Sequence[str],
|
| 148 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
| 149 |
+
) -> dict:
|
| 150 |
+
"""Preprocess the data by tokenizing."""
|
| 151 |
+
examples = [s + t for s, t in zip(sources, targets)]
|
| 152 |
+
examples_tokenized, sources_tokenized = (_tokenize_fn(strings, tokenizer) for strings in (examples, sources))
|
| 153 |
+
input_ids = examples_tokenized["input_ids"]
|
| 154 |
+
labels = copy.deepcopy(input_ids)
|
| 155 |
+
for label, source_len in zip(labels, sources_tokenized["input_ids_lens"]):
|
| 156 |
+
label[:source_len] = IGNORE_INDEX
|
| 157 |
+
return {
|
| 158 |
+
"input_ids": input_ids,
|
| 159 |
+
"labels": labels,
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
@dataclass
|
| 164 |
+
class DataCollatorForSupervisedDataset:
|
| 165 |
+
"""Collate examples for supervised fine-tuning."""
|
| 166 |
+
|
| 167 |
+
tokenizer: transformers.PreTrainedTokenizer
|
| 168 |
+
|
| 169 |
+
def __call__(self, instances: Sequence[dict]) -> dict[str, torch.Tensor]:
|
| 170 |
+
input_ids, labels = tuple([instance[key] for instance in instances] for key in ("input_ids", "labels"))
|
| 171 |
+
input_ids = [torch.tensor(x) for x in input_ids]
|
| 172 |
+
input_ids = torch.nn.utils.rnn.pad_sequence(
|
| 173 |
+
input_ids, batch_first=True, padding_value=self.tokenizer.pad_token_id
|
| 174 |
+
)
|
| 175 |
+
labels = [torch.tensor(x) for x in labels]
|
| 176 |
+
labels = torch.nn.utils.rnn.pad_sequence(labels, batch_first=True, padding_value=IGNORE_INDEX)
|
| 177 |
+
return {
|
| 178 |
+
"input_ids": input_ids,
|
| 179 |
+
"labels": labels,
|
| 180 |
+
"attention_mask": input_ids.ne(self.tokenizer.pad_token_id),
|
| 181 |
+
}
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def train_tokenize_function(examples, tokenizer, query, response):
|
| 185 |
+
sources = [
|
| 186 |
+
PROMPT.format_map(
|
| 187 |
+
{
|
| 188 |
+
"instruction": instruction,
|
| 189 |
+
}
|
| 190 |
+
)
|
| 191 |
+
for instruction in examples[query]
|
| 192 |
+
]
|
| 193 |
+
targets = [f"{output}{tokenizer.eos_token}" for output in examples[response]]
|
| 194 |
+
data_dict = preprocess(sources, targets, tokenizer)
|
| 195 |
+
return data_dict
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def train():
|
| 199 |
+
parser = transformers.HfArgumentParser(TrainingArguments)
|
| 200 |
+
script_args = parser.parse_args_into_dataclasses()[0]
|
| 201 |
+
print(script_args)
|
| 202 |
+
|
| 203 |
+
if script_args.corda_mode:
|
| 204 |
+
print("Train in CorDA mode")
|
| 205 |
+
res_model = transformers.AutoModelForCausalLM.from_pretrained(
|
| 206 |
+
script_args.model_name_or_path,
|
| 207 |
+
device_map="auto",
|
| 208 |
+
)
|
| 209 |
+
model = PeftModel.from_pretrained(
|
| 210 |
+
res_model, script_args.model_name_or_path, subfolder="corda_init", is_trainable=True
|
| 211 |
+
)
|
| 212 |
+
elif script_args.lora_r is not None:
|
| 213 |
+
print("Train in LoRA mode")
|
| 214 |
+
model = transformers.AutoModelForCausalLM.from_pretrained(
|
| 215 |
+
script_args.model_name_or_path,
|
| 216 |
+
device_map="auto",
|
| 217 |
+
)
|
| 218 |
+
lora_config = LoraConfig(
|
| 219 |
+
r=script_args.lora_r,
|
| 220 |
+
lora_alpha=script_args.lora_r,
|
| 221 |
+
init_lora_weights=True, # script_args.init_lora_weights,
|
| 222 |
+
target_modules=["q_proj", "o_proj", "k_proj", "v_proj", "gate_proj", "up_proj", "down_proj"],
|
| 223 |
+
lora_dropout=0,
|
| 224 |
+
bias="none",
|
| 225 |
+
task_type="CAUSAL_LM",
|
| 226 |
+
)
|
| 227 |
+
model = get_peft_model(model, lora_config)
|
| 228 |
+
else:
|
| 229 |
+
print("Train in Full Finetuning mode")
|
| 230 |
+
model = transformers.AutoModelForCausalLM.from_pretrained(
|
| 231 |
+
script_args.model_name_or_path,
|
| 232 |
+
dtype=torch.bfloat16,
|
| 233 |
+
device_map="auto",
|
| 234 |
+
)
|
| 235 |
+
trainable_params, all_param = get_nb_trainable_parameters(model)
|
| 236 |
+
print(
|
| 237 |
+
f"trainable params: {trainable_params:,d} || all params: {all_param:,d} || trainable%: {100 * trainable_params / all_param}"
|
| 238 |
+
)
|
| 239 |
+
tokenizer = transformers.AutoTokenizer.from_pretrained(
|
| 240 |
+
script_args.model_name_or_path,
|
| 241 |
+
model_max_length=script_args.model_max_length,
|
| 242 |
+
padding_side="right",
|
| 243 |
+
use_fast=True,
|
| 244 |
+
trust_remote_code=True,
|
| 245 |
+
)
|
| 246 |
+
tokenizer.pad_token_id = tokenizer.eos_token_id
|
| 247 |
+
|
| 248 |
+
raw_train_datasets = load_dataset(script_args.data_path, split=script_args.dataset_split)
|
| 249 |
+
train_dataset = raw_train_datasets.map(
|
| 250 |
+
train_tokenize_function,
|
| 251 |
+
batched=True,
|
| 252 |
+
batch_size=script_args.dataloader_batch_size,
|
| 253 |
+
num_proc=script_args.dataloader_num_proc,
|
| 254 |
+
remove_columns=raw_train_datasets.column_names,
|
| 255 |
+
load_from_cache_file=True,
|
| 256 |
+
desc="Running tokenizer on train dataset",
|
| 257 |
+
fn_kwargs={
|
| 258 |
+
"tokenizer": tokenizer,
|
| 259 |
+
"query": script_args.dataset_field[0],
|
| 260 |
+
"response": script_args.dataset_field[1],
|
| 261 |
+
},
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer)
|
| 265 |
+
data_module = {
|
| 266 |
+
"train_dataset": train_dataset,
|
| 267 |
+
"data_collator": data_collator,
|
| 268 |
+
}
|
| 269 |
+
trainer = Trainer(model=model, processing_class=tokenizer, args=script_args, **data_module)
|
| 270 |
+
trainer.train()
|
| 271 |
+
trainer.save_state()
|
| 272 |
+
model.save_pretrained(os.path.join(script_args.output_dir, "ft"))
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
if __name__ == "__main__":
|
| 276 |
+
train()
|
tasks/tasksmith-ecb1931929df/tests/source/examples/corda_finetuning/datautils.py
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
import os
|
| 16 |
+
import random
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import torch
|
| 20 |
+
from datasets import load_dataset
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
"""
|
| 24 |
+
doc https://huggingface.co/docs/datasets/loading
|
| 25 |
+
doc https://huggingface.co/docs/datasets/process
|
| 26 |
+
doc https://huggingface.co/blog/llama2#how-to-prompt-llama-2
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def set_seed(seed):
|
| 31 |
+
np.random.seed(seed)
|
| 32 |
+
torch.random.manual_seed(seed)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def sample_train_loaders(name, tokenizer, nsamples=128, seed=0, seqlen=2048):
|
| 36 |
+
set_seed(seed)
|
| 37 |
+
if "wikitext2" in name:
|
| 38 |
+
traindata = load_dataset(
|
| 39 |
+
"wikitext",
|
| 40 |
+
"wikitext-2-raw-v1",
|
| 41 |
+
split="train",
|
| 42 |
+
)
|
| 43 |
+
traindata = "\n\n".join(traindata["text"])
|
| 44 |
+
elif "c4" in name:
|
| 45 |
+
traindata = load_dataset(
|
| 46 |
+
"allenai/c4",
|
| 47 |
+
"allenai--c4",
|
| 48 |
+
data_files={"train": "en/c4-train.00000-of-01024.json.gz"},
|
| 49 |
+
split="train",
|
| 50 |
+
)
|
| 51 |
+
traindata = "\n\n".join(traindata["text"])
|
| 52 |
+
else:
|
| 53 |
+
raise NotImplementedError
|
| 54 |
+
|
| 55 |
+
trainloader = []
|
| 56 |
+
for _ in range(nsamples):
|
| 57 |
+
i = random.randint(0, len(traindata) - seqlen * 2 - 1)
|
| 58 |
+
j = i + seqlen * 2
|
| 59 |
+
# breakpoint()
|
| 60 |
+
trainenc = tokenizer(traindata[i:j], return_tensors="pt")
|
| 61 |
+
inp = trainenc.input_ids[:, :seqlen]
|
| 62 |
+
trainloader.append(inp)
|
| 63 |
+
return trainloader
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def get_redpajama_train(tokenizer, percent=10, seed=3, batch_size=128, max_length=2048):
|
| 67 |
+
def tokenization(example):
|
| 68 |
+
return tokenizer(example["text"], truncation=True, max_length=max_length)
|
| 69 |
+
|
| 70 |
+
if percent != 100:
|
| 71 |
+
split = f"train[:{int(850000 * percent / 100)}]"
|
| 72 |
+
else:
|
| 73 |
+
split = "train"
|
| 74 |
+
dataset = load_dataset("togethercomputer/RedPajama-Data-1T-Sample", split=split)
|
| 75 |
+
|
| 76 |
+
processed_dataset = dataset.map(tokenization, batched=True, batch_size=batch_size, num_proc=os.cpu_count())
|
| 77 |
+
return processed_dataset
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def get_english_quote(dataset_name, tokenizer):
|
| 81 |
+
data = load_dataset(dataset_name)
|
| 82 |
+
data = data.map(lambda samples: tokenizer(samples["quote"]), batched=True)
|
| 83 |
+
return data["train"]
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def get_qat_dataset(name, tokenizer, data_percent):
|
| 87 |
+
if name == "red_pajama":
|
| 88 |
+
data = get_redpajama_train(tokenizer, data_percent)
|
| 89 |
+
|
| 90 |
+
elif name == "Abirate/english_quotes":
|
| 91 |
+
data = get_english_quote(name, tokenizer)
|
| 92 |
+
else:
|
| 93 |
+
raise NotImplementedError
|
| 94 |
+
data = data.shuffle()
|
| 95 |
+
return data
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
llama_chat_format = """<s>[INST] <<SYS>>
|
| 99 |
+
"Below is an instruction that describes a task. Write a response that appropriately completes the request."
|
| 100 |
+
<</SYS>>
|
| 101 |
+
|
| 102 |
+
{instruction} [/INST] {response} </s>
|
| 103 |
+
"""
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def get_calib_data(name, tokenizer, model_id, nsamples, seqlen=2048, seed=3):
|
| 107 |
+
print(f" get_data_from: {name}, nsamples={nsamples}, seqlen={seqlen}, {seed}")
|
| 108 |
+
cache_file = f"cache/{name}_{model_id.replace('/', '_')}_{nsamples}_{seqlen}_{seed}.pt"
|
| 109 |
+
traindataset = []
|
| 110 |
+
if not os.path.exists("cache"):
|
| 111 |
+
os.makedirs("cache")
|
| 112 |
+
if os.path.exists(cache_file):
|
| 113 |
+
print(f"found data file: {cache_file}")
|
| 114 |
+
traindataset = torch.load(cache_file)
|
| 115 |
+
print("loaded ...")
|
| 116 |
+
return traindataset
|
| 117 |
+
if name == "c4":
|
| 118 |
+
traindata = load_dataset(
|
| 119 |
+
"allenai/c4",
|
| 120 |
+
"allenai--c4",
|
| 121 |
+
data_files={"train": "en/c4-train.00000-of-01024.json.gz"},
|
| 122 |
+
split="train",
|
| 123 |
+
)
|
| 124 |
+
tot_text = "\n\n".join(traindata["text"])
|
| 125 |
+
elif name == "wikitext2":
|
| 126 |
+
traindata = load_dataset("wikitext", "wikitext-2-raw-v1", split="train")
|
| 127 |
+
tot_text = "\n\n".join(traindata["text"])
|
| 128 |
+
elif name == "ptb":
|
| 129 |
+
traindata = load_dataset(
|
| 130 |
+
"ptb_text_only",
|
| 131 |
+
"penn_treebank",
|
| 132 |
+
split="train",
|
| 133 |
+
)
|
| 134 |
+
tot_text = "\n\n".join(traindata["sentence"])
|
| 135 |
+
elif name == "traivia_qa":
|
| 136 |
+
traindata = load_dataset("trivia_qa", "rc", split="train")
|
| 137 |
+
tot_text = "\n\n".join(traindata["question"])
|
| 138 |
+
elif name == "nqopen":
|
| 139 |
+
traindata = load_dataset("nq_open", split="train")
|
| 140 |
+
tot_text = "\n\n".join(traindata["question"])
|
| 141 |
+
elif name == "alpaca":
|
| 142 |
+
selected_data_dict = load_dataset("iboing/alpaca_data", split="train").shuffle(seed=seed).take(nsamples)
|
| 143 |
+
for example in selected_data_dict:
|
| 144 |
+
if example.get("input", "") == "":
|
| 145 |
+
s = llama_chat_format.format(instruction=example["instruction"], response=example["output"])
|
| 146 |
+
trainenc = tokenizer(s, return_tensors="pt")
|
| 147 |
+
inp = trainenc.input_ids[:, :seqlen]
|
| 148 |
+
attention_mask = torch.ones_like(inp)
|
| 149 |
+
traindataset.append({"input_ids": inp, "attention_mask": attention_mask})
|
| 150 |
+
print("example instruction:", s)
|
| 151 |
+
torch.save(traindataset, cache_file)
|
| 152 |
+
return traindataset
|
| 153 |
+
elif name == "MetaMATH":
|
| 154 |
+
selected_data_dict = load_dataset("iboing/MetaMathQA-395K", split="train").shuffle(seed=seed).take(nsamples)
|
| 155 |
+
for example in selected_data_dict:
|
| 156 |
+
if example.get("input", "") == "":
|
| 157 |
+
s = llama_chat_format.format(instruction=example["query"], response=example["response"])
|
| 158 |
+
trainenc = tokenizer(s, return_tensors="pt")
|
| 159 |
+
inp = trainenc.input_ids[:, :seqlen]
|
| 160 |
+
attention_mask = torch.ones_like(inp)
|
| 161 |
+
traindataset.append({"input_ids": inp, "attention_mask": attention_mask})
|
| 162 |
+
print("example instruction:", s)
|
| 163 |
+
torch.save(traindataset, cache_file)
|
| 164 |
+
return traindataset
|
| 165 |
+
elif name == "codefeedback":
|
| 166 |
+
selected_data_dict = (
|
| 167 |
+
load_dataset("iboing/CodeFeedback-Filtered-Instruction", split="train").shuffle(seed=seed).take(nsamples)
|
| 168 |
+
)
|
| 169 |
+
for example in selected_data_dict:
|
| 170 |
+
if example.get("input", "") == "":
|
| 171 |
+
s = llama_chat_format.format(instruction=example["query"], response=example["answer"])
|
| 172 |
+
trainenc = tokenizer(s, return_tensors="pt")
|
| 173 |
+
inp = trainenc.input_ids[:, :seqlen]
|
| 174 |
+
attention_mask = torch.ones_like(inp)
|
| 175 |
+
traindataset.append({"input_ids": inp, "attention_mask": attention_mask})
|
| 176 |
+
print("example instruction:", s)
|
| 177 |
+
torch.save(traindataset, cache_file)
|
| 178 |
+
return traindataset
|
| 179 |
+
elif name == "WizLMinstruct":
|
| 180 |
+
selected_data_dict = (
|
| 181 |
+
load_dataset("iboing/WizardLM_evol_instruct_V2_143k", split="train").shuffle(seed=seed).take(nsamples)
|
| 182 |
+
)
|
| 183 |
+
for example in selected_data_dict:
|
| 184 |
+
if example.get("input", "") == "":
|
| 185 |
+
s = llama_chat_format.format(
|
| 186 |
+
instruction=example["conversation"][0]["human"], response=example["conversation"][0]["assistant"]
|
| 187 |
+
)
|
| 188 |
+
trainenc = tokenizer(s, return_tensors="pt")
|
| 189 |
+
inp = trainenc.input_ids[:, :seqlen]
|
| 190 |
+
attention_mask = torch.ones_like(inp)
|
| 191 |
+
traindataset.append({"input_ids": inp, "attention_mask": attention_mask})
|
| 192 |
+
print("example instruction:", s)
|
| 193 |
+
torch.save(traindataset, cache_file)
|
| 194 |
+
return traindataset
|
| 195 |
+
else:
|
| 196 |
+
raise NotImplementedError
|
| 197 |
+
print(f"tot_text={len(tot_text)}")
|
| 198 |
+
for _ in range(nsamples):
|
| 199 |
+
i = random.randint(0, len(tot_text) - seqlen - 1)
|
| 200 |
+
j = i + seqlen * 10
|
| 201 |
+
trainenc = tokenizer(tot_text[i:j], return_tensors="pt")
|
| 202 |
+
inp = trainenc.input_ids[:, :seqlen]
|
| 203 |
+
attention_mask = torch.ones_like(inp)
|
| 204 |
+
traindataset.append({"input_ids": inp, "attention_mask": attention_mask})
|
| 205 |
+
torch.save(traindataset, cache_file)
|
| 206 |
+
return traindataset
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def get_eval_loaders(name, tokenizer):
|
| 210 |
+
if "wikitext2" in name:
|
| 211 |
+
testdata = load_dataset(
|
| 212 |
+
"wikitext",
|
| 213 |
+
"wikitext-2-raw-v1",
|
| 214 |
+
split="test",
|
| 215 |
+
)
|
| 216 |
+
testenc = tokenizer("\n\n".join(testdata["text"]), return_tensors="pt")
|
| 217 |
+
return testenc
|
| 218 |
+
if "ptb" in name:
|
| 219 |
+
valdata = load_dataset(
|
| 220 |
+
"ptb_text_only",
|
| 221 |
+
"penn_treebank",
|
| 222 |
+
split="validation",
|
| 223 |
+
)
|
| 224 |
+
testenc = tokenizer("\n\n".join(valdata["sentence"]), return_tensors="pt")
|
| 225 |
+
return testenc
|
| 226 |
+
if "c4" in name:
|
| 227 |
+
testdata = load_dataset(
|
| 228 |
+
"allenai/c4",
|
| 229 |
+
"allenai--c4",
|
| 230 |
+
data_files={"validation": "en/c4-validation.00000-of-00008.json.gz"},
|
| 231 |
+
split="validation",
|
| 232 |
+
)
|
| 233 |
+
testenc = tokenizer("\n\n".join(testdata["text"]), return_tensors="pt")
|
| 234 |
+
return testenc
|
| 235 |
+
raise NotImplementedError
|
tasks/tasksmith-ecb1931929df/tests/source/examples/corda_finetuning/preprocess.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
import argparse
|
| 16 |
+
import os
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import torch
|
| 20 |
+
from datautils import get_calib_data
|
| 21 |
+
from tqdm import tqdm
|
| 22 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 23 |
+
|
| 24 |
+
from peft import get_peft_model
|
| 25 |
+
from peft.tuners.lora.config import CordaConfig, LoraConfig
|
| 26 |
+
from peft.tuners.lora.corda import preprocess_corda
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@torch.no_grad()
|
| 30 |
+
def run_model(model, calib_loader):
|
| 31 |
+
model.eval()
|
| 32 |
+
for batch in tqdm(calib_loader):
|
| 33 |
+
batch = {k: v.to(model.device) for k, v in batch.items()}
|
| 34 |
+
model(**batch)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def main(args):
|
| 38 |
+
# Setting random seed of numpy and torch
|
| 39 |
+
np.random.seed(args.seed)
|
| 40 |
+
torch.manual_seed(args.seed)
|
| 41 |
+
if torch.cuda.is_available():
|
| 42 |
+
torch.cuda.manual_seed_all(args.seed)
|
| 43 |
+
elif torch.xpu.is_available():
|
| 44 |
+
torch.xpu.manual_seed_all(args.seed)
|
| 45 |
+
torch.use_deterministic_algorithms(True)
|
| 46 |
+
|
| 47 |
+
# Load model
|
| 48 |
+
model_id = args.model_id
|
| 49 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
|
| 50 |
+
|
| 51 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 52 |
+
model_id, device_map="auto", dtype=torch.float16, trust_remote_code=True
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
# Collect data
|
| 56 |
+
calib_loader = get_calib_data(args.calib_dataset, tokenizer, model_id, args.calib_loader_size, seed=args.seed)
|
| 57 |
+
|
| 58 |
+
# Evaluate the original model
|
| 59 |
+
print("\n---- model before svd ---\n")
|
| 60 |
+
print(model)
|
| 61 |
+
|
| 62 |
+
# Perform decomposition
|
| 63 |
+
corda_config = CordaConfig(
|
| 64 |
+
corda_method="ipm" if args.first_eigen else "kpm",
|
| 65 |
+
)
|
| 66 |
+
lora_config = LoraConfig(
|
| 67 |
+
init_lora_weights="corda",
|
| 68 |
+
target_modules=["q_proj", "o_proj", "k_proj", "v_proj", "gate_proj", "up_proj", "down_proj"],
|
| 69 |
+
r=args.r,
|
| 70 |
+
lora_alpha=args.r,
|
| 71 |
+
corda_config=corda_config,
|
| 72 |
+
)
|
| 73 |
+
preprocess_corda(
|
| 74 |
+
model,
|
| 75 |
+
lora_config,
|
| 76 |
+
run_model=lambda: run_model(model, calib_loader),
|
| 77 |
+
)
|
| 78 |
+
model = get_peft_model(model, lora_config)
|
| 79 |
+
|
| 80 |
+
# Evaluate again to check if the model is consistent
|
| 81 |
+
# Using `model.model` here because `get_peft_model` wraps a layer to the model
|
| 82 |
+
print("\n---- model after svd ---\n")
|
| 83 |
+
print(model)
|
| 84 |
+
|
| 85 |
+
# Save as hugging face model
|
| 86 |
+
if args.save_model:
|
| 87 |
+
assert args.save_path is not None
|
| 88 |
+
save_path = args.save_path
|
| 89 |
+
|
| 90 |
+
# Save CorDA modules
|
| 91 |
+
model.peft_config["default"].init_lora_weights = True
|
| 92 |
+
model.save_pretrained(os.path.join(save_path, "corda_init"))
|
| 93 |
+
|
| 94 |
+
# Save residual model
|
| 95 |
+
model = model.unload()
|
| 96 |
+
model.save_pretrained(save_path)
|
| 97 |
+
|
| 98 |
+
# Save tokenizer
|
| 99 |
+
tokenizer.save_pretrained(save_path)
|
| 100 |
+
print(f"Done building CorDA huggingface model in {save_path}")
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
if __name__ == "__main__":
|
| 104 |
+
parser = argparse.ArgumentParser()
|
| 105 |
+
parser.add_argument(
|
| 106 |
+
"--model_id",
|
| 107 |
+
type=str,
|
| 108 |
+
default="meta-llama/Llama-2-7b-hf",
|
| 109 |
+
help="Pretrained model ID",
|
| 110 |
+
)
|
| 111 |
+
parser.add_argument(
|
| 112 |
+
"--calib_loader_size",
|
| 113 |
+
type=int,
|
| 114 |
+
default=256,
|
| 115 |
+
help="number of samples used for covariance matrices",
|
| 116 |
+
)
|
| 117 |
+
parser.add_argument(
|
| 118 |
+
"--calib_dataset",
|
| 119 |
+
type=str,
|
| 120 |
+
default="wikitext2",
|
| 121 |
+
choices=[
|
| 122 |
+
"wikitext2",
|
| 123 |
+
"c4",
|
| 124 |
+
"ptb",
|
| 125 |
+
"traivia_qa",
|
| 126 |
+
"nqopen",
|
| 127 |
+
"MetaMATH",
|
| 128 |
+
"codefeedback",
|
| 129 |
+
"WizLMinstruct",
|
| 130 |
+
"alpaca",
|
| 131 |
+
],
|
| 132 |
+
help="calibration dataset",
|
| 133 |
+
)
|
| 134 |
+
parser.add_argument(
|
| 135 |
+
"--eval_mmlu",
|
| 136 |
+
action="store_true",
|
| 137 |
+
help="evaluate mmlu",
|
| 138 |
+
)
|
| 139 |
+
parser.add_argument(
|
| 140 |
+
"--seed",
|
| 141 |
+
type=int,
|
| 142 |
+
default=233,
|
| 143 |
+
help="random seed",
|
| 144 |
+
)
|
| 145 |
+
parser.add_argument(
|
| 146 |
+
"--r",
|
| 147 |
+
type=int,
|
| 148 |
+
default=None,
|
| 149 |
+
)
|
| 150 |
+
parser.add_argument(
|
| 151 |
+
"--first_eigen",
|
| 152 |
+
action="store_true",
|
| 153 |
+
)
|
| 154 |
+
parser.add_argument(
|
| 155 |
+
"--save_model",
|
| 156 |
+
action="store_true",
|
| 157 |
+
)
|
| 158 |
+
parser.add_argument(
|
| 159 |
+
"--save_path",
|
| 160 |
+
type=str,
|
| 161 |
+
default=None,
|
| 162 |
+
)
|
| 163 |
+
args = parser.parse_args()
|
| 164 |
+
|
| 165 |
+
main(args)
|
tasks/tasksmith-ecb1931929df/tests/source/examples/cpt_finetuning/README.md
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
# Context-aware Prompt Tuning: Advancing In-Context Learning with Adversarial Methods
|
| 3 |
+
## Introduction ([Paper](https://huggingface.co/papers/2410.17222), [Code](https://github.com/tsachiblau/Context-aware-Prompt-Tuning-Advancing-In-Context-Learning-with-Adversarial-Methods), [Notebook](cpt_train_and_inference.ipynb), [Colab](https://colab.research.google.com/drive/1UhQDVhZ9bDlSk1551SuJV8tIUmlIayta?usp=sharing))
|
| 4 |
+
|
| 5 |
+
> Large Language Models (LLMs) can perform few-shot learning using either optimization-based approaches or In-Context Learning (ICL). Optimization-based methods often suffer from overfitting, as they require updating a large number of parameters with limited data. In contrast, ICL avoids overfitting but typically underperforms compared to optimization-based methods and is highly sensitive to the selection, order, and format of demonstration examples. To overcome these challenges, we introduce Context-aware Prompt Tuning (CPT), a method inspired by ICL, Prompt Tuning (PT), and adversarial attacks. CPT builds on the ICL strategy of concatenating examples before the input, extending it by incorporating PT-like learning to refine the context embedding through iterative optimization, extracting deeper insights from the training examples. Our approach carefully modifies specific context tokens, considering the unique structure of the examples within the context. In addition to updating the context with PT-like optimization, CPT draws inspiration from adversarial attacks, adjusting the input based on the labels present in the context while preserving the inherent value of the user-provided data. To ensure robustness and stability during optimization, we employ a projected gradient descent algorithm, constraining token embeddings to remain close to their original values and safeguarding the quality of the context. Our method has demonstrated superior accuracy across multiple classification tasks using various LLM models, outperforming existing baselines and effectively addressing the overfitting challenge in few-shot learning.
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
<div class="flex justify-center">
|
| 10 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/cpt.png"/>
|
| 11 |
+
</div>
|
| 12 |
+
<small>CPT optimizing only specific token embeddings while keeping the rest of the model frozen <a href="https://huggingface.co/papers/2410.17222">(image source)</a>.</small>
|
| 13 |
+
|
| 14 |
+
---
|
| 15 |
+
|
| 16 |
+
## Dataset Creation and Collation for CPT
|
| 17 |
+
|
| 18 |
+
This document explains how to prepare datasets for CPT, linking the dataset preparation processes in the code to the methods and principles described in the CPT paper, specifically in **Sections 3.1**, **3.2**, and **3.3**.
|
| 19 |
+
|
| 20 |
+
---
|
| 21 |
+
|
| 22 |
+
### Template-Based Tokenization
|
| 23 |
+
|
| 24 |
+
#### The Role of Templates
|
| 25 |
+
Templates define the structure of the input-output pairs, enabling the model to interpret the task within a unified context.
|
| 26 |
+
|
| 27 |
+
- **Input Templates**:
|
| 28 |
+
Templates like `"input: {sentence}"` structure raw input sentences. The `{sentence}` placeholder is replaced with the actual input text.
|
| 29 |
+
|
| 30 |
+
- **Output Templates**:
|
| 31 |
+
Templates such as `"output: {label}"` format the labels (e.g., `positive`, `negative`, etc.).
|
| 32 |
+
|
| 33 |
+
- **Separator Tokens**:
|
| 34 |
+
Separators distinguish different parts of the input, such as the input text and labels, as well as separate examples within the context.
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
#### How CPT Utilizes Context Structure
|
| 38 |
+
|
| 39 |
+
CPT leverages the context structure, encoded within the `cpt_tokens_type_mask`, to optimize the context effectively. to optimize the context effectively. By treating different token types based on their roles, the model updates some tokens while using others solely for optimization:
|
| 40 |
+
|
| 41 |
+
1. **Refrain from Updating Label Tokens**:
|
| 42 |
+
Some context tokens represent label tokens, which contain valuable, unmodifiable information. By excluding these tokens from updates during training, CPT ensures that the labels remain fixed, preserving their integrity.
|
| 43 |
+
|
| 44 |
+
2. **Apply Type-Specific Projection Norms**:
|
| 45 |
+
CPT employs Projected Gradient Descent (PGD) to update context embeddings, applying tailored norms to different context parts. This approach reduces overfitting while maintaining robustness and generalization by preserving the integrity of user-provided examples.
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
#### Limitations
|
| 50 |
+
CPT is designed for few-shot scenarios, as concatenating more examples increases memory usage due to the self-attention mechanism and additional loss terms. For larger datasets, users can limit the number of context examples and use the remaining samples solely for optimization to manage memory efficiently.
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
## Citation
|
| 56 |
+
```bib
|
| 57 |
+
@article{
|
| 58 |
+
blau2025cpt,
|
| 59 |
+
title={Context-Aware Prompt Tuning: Advancing In-Context Learning with Adversarial Methods},
|
| 60 |
+
author={Tsachi Blau, Moshe Kimhi, Yonatan Belinkov, Alexander Bronstein, Chaim Baskin},
|
| 61 |
+
journal={arXiv preprint arXiv:2410.17222}},
|
| 62 |
+
year={2025}
|
| 63 |
+
}
|
| 64 |
+
```
|
tasks/tasksmith-ecb1931929df/tests/source/examples/cpt_finetuning/cpt_train_and_inference.ipynb
ADDED
|
@@ -0,0 +1,1555 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "markdown",
|
| 5 |
+
"source": [
|
| 6 |
+
"# CPT Training and Inference\n",
|
| 7 |
+
"This notebook demonstrates the training and evaluation process of Context-Aware Prompt Tuning (CPT) using the Hugging Face Trainer. For more details, refer to the [Paper](https://huggingface.co/papers/2410.17222).\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"\n",
|
| 10 |
+
"## Sections Overview:\n",
|
| 11 |
+
"1. **Setup**: Import libraries and configure the environment.\n",
|
| 12 |
+
"2. **Data Preparation**: Load and preprocess the dataset.\n",
|
| 13 |
+
"3. **Model Training**: Configure and train the model.\n",
|
| 14 |
+
"4. **Evaluation**: Test the model's performance and visualize results."
|
| 15 |
+
],
|
| 16 |
+
"metadata": {
|
| 17 |
+
"id": "R_byvXT9lpTU"
|
| 18 |
+
},
|
| 19 |
+
"id": "R_byvXT9lpTU"
|
| 20 |
+
},
|
| 21 |
+
{
|
| 22 |
+
"cell_type": "markdown",
|
| 23 |
+
"source": [
|
| 24 |
+
"# Setup\n",
|
| 25 |
+
"\n",
|
| 26 |
+
"---\n",
|
| 27 |
+
"\n",
|
| 28 |
+
"\n"
|
| 29 |
+
],
|
| 30 |
+
"metadata": {
|
| 31 |
+
"collapsed": false,
|
| 32 |
+
"id": "11b07b07ac5e472b"
|
| 33 |
+
},
|
| 34 |
+
"id": "11b07b07ac5e472b"
|
| 35 |
+
},
|
| 36 |
+
{
|
| 37 |
+
"cell_type": "markdown",
|
| 38 |
+
"source": [
|
| 39 |
+
"## Installation"
|
| 40 |
+
],
|
| 41 |
+
"metadata": {
|
| 42 |
+
"id": "O8DWZb8ZrGRU"
|
| 43 |
+
},
|
| 44 |
+
"id": "O8DWZb8ZrGRU"
|
| 45 |
+
},
|
| 46 |
+
{
|
| 47 |
+
"cell_type": "code",
|
| 48 |
+
"source": [
|
| 49 |
+
"!pip install datasets\n",
|
| 50 |
+
"!pip install git+https://github.com/huggingface/peft"
|
| 51 |
+
],
|
| 52 |
+
"metadata": {
|
| 53 |
+
"colab": {
|
| 54 |
+
"base_uri": "https://localhost:8080/"
|
| 55 |
+
},
|
| 56 |
+
"id": "d6KZ5REDrFiM",
|
| 57 |
+
"outputId": "e505bc0e-082a-4720-9117-b730d9fd67fa"
|
| 58 |
+
},
|
| 59 |
+
"id": "d6KZ5REDrFiM",
|
| 60 |
+
"execution_count": 1,
|
| 61 |
+
"outputs": [
|
| 62 |
+
{
|
| 63 |
+
"output_type": "stream",
|
| 64 |
+
"name": "stdout",
|
| 65 |
+
"text": [
|
| 66 |
+
"Requirement already satisfied: datasets in /usr/local/lib/python3.10/dist-packages (3.1.0)\n",
|
| 67 |
+
"Requirement already satisfied: filelock in /usr/local/lib/python3.10/dist-packages (from datasets) (3.16.1)\n",
|
| 68 |
+
"Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.10/dist-packages (from datasets) (1.26.4)\n",
|
| 69 |
+
"Requirement already satisfied: pyarrow>=15.0.0 in /usr/local/lib/python3.10/dist-packages (from datasets) (17.0.0)\n",
|
| 70 |
+
"Requirement already satisfied: dill<0.3.9,>=0.3.0 in /usr/local/lib/python3.10/dist-packages (from datasets) (0.3.8)\n",
|
| 71 |
+
"Requirement already satisfied: pandas in /usr/local/lib/python3.10/dist-packages (from datasets) (2.2.2)\n",
|
| 72 |
+
"Requirement already satisfied: requests>=2.32.2 in /usr/local/lib/python3.10/dist-packages (from datasets) (2.32.3)\n",
|
| 73 |
+
"Requirement already satisfied: tqdm>=4.66.3 in /usr/local/lib/python3.10/dist-packages (from datasets) (4.66.6)\n",
|
| 74 |
+
"Requirement already satisfied: xxhash in /usr/local/lib/python3.10/dist-packages (from datasets) (3.5.0)\n",
|
| 75 |
+
"Requirement already satisfied: multiprocess<0.70.17 in /usr/local/lib/python3.10/dist-packages (from datasets) (0.70.16)\n",
|
| 76 |
+
"Requirement already satisfied: fsspec<=2024.9.0,>=2023.1.0 in /usr/local/lib/python3.10/dist-packages (from fsspec[http]<=2024.9.0,>=2023.1.0->datasets) (2024.9.0)\n",
|
| 77 |
+
"Requirement already satisfied: aiohttp in /usr/local/lib/python3.10/dist-packages (from datasets) (3.11.2)\n",
|
| 78 |
+
"Requirement already satisfied: huggingface-hub>=0.23.0 in /usr/local/lib/python3.10/dist-packages (from datasets) (0.26.2)\n",
|
| 79 |
+
"Requirement already satisfied: packaging in /usr/local/lib/python3.10/dist-packages (from datasets) (24.2)\n",
|
| 80 |
+
"Requirement already satisfied: pyyaml>=5.1 in /usr/local/lib/python3.10/dist-packages (from datasets) (6.0.2)\n",
|
| 81 |
+
"Requirement already satisfied: aiohappyeyeballs>=2.3.0 in /usr/local/lib/python3.10/dist-packages (from aiohttp->datasets) (2.4.3)\n",
|
| 82 |
+
"Requirement already satisfied: aiosignal>=1.1.2 in /usr/local/lib/python3.10/dist-packages (from aiohttp->datasets) (1.3.1)\n",
|
| 83 |
+
"Requirement already satisfied: attrs>=17.3.0 in /usr/local/lib/python3.10/dist-packages (from aiohttp->datasets) (24.2.0)\n",
|
| 84 |
+
"Requirement already satisfied: frozenlist>=1.1.1 in /usr/local/lib/python3.10/dist-packages (from aiohttp->datasets) (1.5.0)\n",
|
| 85 |
+
"Requirement already satisfied: multidict<7.0,>=4.5 in /usr/local/lib/python3.10/dist-packages (from aiohttp->datasets) (6.1.0)\n",
|
| 86 |
+
"Requirement already satisfied: propcache>=0.2.0 in /usr/local/lib/python3.10/dist-packages (from aiohttp->datasets) (0.2.0)\n",
|
| 87 |
+
"Requirement already satisfied: yarl<2.0,>=1.17.0 in /usr/local/lib/python3.10/dist-packages (from aiohttp->datasets) (1.17.2)\n",
|
| 88 |
+
"Requirement already satisfied: async-timeout<6.0,>=4.0 in /usr/local/lib/python3.10/dist-packages (from aiohttp->datasets) (4.0.3)\n",
|
| 89 |
+
"Requirement already satisfied: typing-extensions>=3.7.4.3 in /usr/local/lib/python3.10/dist-packages (from huggingface-hub>=0.23.0->datasets) (4.12.2)\n",
|
| 90 |
+
"Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.10/dist-packages (from requests>=2.32.2->datasets) (3.4.0)\n",
|
| 91 |
+
"Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.10/dist-packages (from requests>=2.32.2->datasets) (3.10)\n",
|
| 92 |
+
"Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.10/dist-packages (from requests>=2.32.2->datasets) (2.2.3)\n",
|
| 93 |
+
"Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.10/dist-packages (from requests>=2.32.2->datasets) (2024.8.30)\n",
|
| 94 |
+
"Requirement already satisfied: python-dateutil>=2.8.2 in /usr/local/lib/python3.10/dist-packages (from pandas->datasets) (2.8.2)\n",
|
| 95 |
+
"Requirement already satisfied: pytz>=2020.1 in /usr/local/lib/python3.10/dist-packages (from pandas->datasets) (2024.2)\n",
|
| 96 |
+
"Requirement already satisfied: tzdata>=2022.7 in /usr/local/lib/python3.10/dist-packages (from pandas->datasets) (2024.2)\n",
|
| 97 |
+
"Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.10/dist-packages (from python-dateutil>=2.8.2->pandas->datasets) (1.16.0)\n",
|
| 98 |
+
"Collecting git+https://github.com/huggingface/peft\n",
|
| 99 |
+
" Cloning https://github.com/huggingface/peft to /tmp/pip-req-build-0mbyx_z_\n",
|
| 100 |
+
" Running command git clone --filter=blob:none --quiet https://github.com/huggingface/peft /tmp/pip-req-build-0mbyx_z_\n",
|
| 101 |
+
" Resolved https://github.com/huggingface/peft to commit 131efba5d48753a3355ecd4f3833ae010a0510d6\n",
|
| 102 |
+
" Installing build dependencies ... \u001b[?25l\u001b[?25hdone\n",
|
| 103 |
+
" Getting requirements to build wheel ... \u001b[?25l\u001b[?25hdone\n",
|
| 104 |
+
" Preparing metadata (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n",
|
| 105 |
+
"Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.10/dist-packages (from peft==0.13.3.dev0) (1.26.4)\n",
|
| 106 |
+
"Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.10/dist-packages (from peft==0.13.3.dev0) (24.2)\n",
|
| 107 |
+
"Requirement already satisfied: psutil in /usr/local/lib/python3.10/dist-packages (from peft==0.13.3.dev0) (5.9.5)\n",
|
| 108 |
+
"Requirement already satisfied: pyyaml in /usr/local/lib/python3.10/dist-packages (from peft==0.13.3.dev0) (6.0.2)\n",
|
| 109 |
+
"Requirement already satisfied: torch>=1.13.0 in /usr/local/lib/python3.10/dist-packages (from peft==0.13.3.dev0) (2.5.1+cu121)\n",
|
| 110 |
+
"Requirement already satisfied: transformers in /usr/local/lib/python3.10/dist-packages (from peft==0.13.3.dev0) (4.46.2)\n",
|
| 111 |
+
"Requirement already satisfied: tqdm in /usr/local/lib/python3.10/dist-packages (from peft==0.13.3.dev0) (4.66.6)\n",
|
| 112 |
+
"Requirement already satisfied: accelerate>=0.21.0 in /usr/local/lib/python3.10/dist-packages (from peft==0.13.3.dev0) (1.1.1)\n",
|
| 113 |
+
"Requirement already satisfied: safetensors in /usr/local/lib/python3.10/dist-packages (from peft==0.13.3.dev0) (0.4.5)\n",
|
| 114 |
+
"Requirement already satisfied: huggingface_hub>=0.25.0 in /usr/local/lib/python3.10/dist-packages (from peft==0.13.3.dev0) (0.26.2)\n",
|
| 115 |
+
"Requirement already satisfied: filelock in /usr/local/lib/python3.10/dist-packages (from huggingface_hub>=0.25.0->peft==0.13.3.dev0) (3.16.1)\n",
|
| 116 |
+
"Requirement already satisfied: fsspec>=2023.5.0 in /usr/local/lib/python3.10/dist-packages (from huggingface_hub>=0.25.0->peft==0.13.3.dev0) (2024.9.0)\n",
|
| 117 |
+
"Requirement already satisfied: requests in /usr/local/lib/python3.10/dist-packages (from huggingface_hub>=0.25.0->peft==0.13.3.dev0) (2.32.3)\n",
|
| 118 |
+
"Requirement already satisfied: typing-extensions>=3.7.4.3 in /usr/local/lib/python3.10/dist-packages (from huggingface_hub>=0.25.0->peft==0.13.3.dev0) (4.12.2)\n",
|
| 119 |
+
"Requirement already satisfied: networkx in /usr/local/lib/python3.10/dist-packages (from torch>=1.13.0->peft==0.13.3.dev0) (3.4.2)\n",
|
| 120 |
+
"Requirement already satisfied: jinja2 in /usr/local/lib/python3.10/dist-packages (from torch>=1.13.0->peft==0.13.3.dev0) (3.1.4)\n",
|
| 121 |
+
"Requirement already satisfied: sympy==1.13.1 in /usr/local/lib/python3.10/dist-packages (from torch>=1.13.0->peft==0.13.3.dev0) (1.13.1)\n",
|
| 122 |
+
"Requirement already satisfied: mpmath<1.4,>=1.1.0 in /usr/local/lib/python3.10/dist-packages (from sympy==1.13.1->torch>=1.13.0->peft==0.13.3.dev0) (1.3.0)\n",
|
| 123 |
+
"Requirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.10/dist-packages (from transformers->peft==0.13.3.dev0) (2024.9.11)\n",
|
| 124 |
+
"Requirement already satisfied: tokenizers<0.21,>=0.20 in /usr/local/lib/python3.10/dist-packages (from transformers->peft==0.13.3.dev0) (0.20.3)\n",
|
| 125 |
+
"Requirement already satisfied: MarkupSafe>=2.0 in /usr/local/lib/python3.10/dist-packages (from jinja2->torch>=1.13.0->peft==0.13.3.dev0) (3.0.2)\n",
|
| 126 |
+
"Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.10/dist-packages (from requests->huggingface_hub>=0.25.0->peft==0.13.3.dev0) (3.4.0)\n",
|
| 127 |
+
"Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.10/dist-packages (from requests->huggingface_hub>=0.25.0->peft==0.13.3.dev0) (3.10)\n",
|
| 128 |
+
"Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.10/dist-packages (from requests->huggingface_hub>=0.25.0->peft==0.13.3.dev0) (2.2.3)\n",
|
| 129 |
+
"Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.10/dist-packages (from requests->huggingface_hub>=0.25.0->peft==0.13.3.dev0) (2024.8.30)\n"
|
| 130 |
+
]
|
| 131 |
+
}
|
| 132 |
+
]
|
| 133 |
+
},
|
| 134 |
+
{
|
| 135 |
+
"cell_type": "markdown",
|
| 136 |
+
"source": [
|
| 137 |
+
"## Imports"
|
| 138 |
+
],
|
| 139 |
+
"metadata": {
|
| 140 |
+
"id": "5BerCvfkq_jp"
|
| 141 |
+
},
|
| 142 |
+
"id": "5BerCvfkq_jp"
|
| 143 |
+
},
|
| 144 |
+
{
|
| 145 |
+
"cell_type": "code",
|
| 146 |
+
"source": [
|
| 147 |
+
"from typing import Any, Dict, List, Union\n",
|
| 148 |
+
"\n",
|
| 149 |
+
"import numpy as np\n",
|
| 150 |
+
"import torch\n",
|
| 151 |
+
"from datasets import load_dataset\n",
|
| 152 |
+
"from torch.utils.data import Dataset\n",
|
| 153 |
+
"from tqdm import tqdm\n",
|
| 154 |
+
"from transformers import (\n",
|
| 155 |
+
" AutoModelForCausalLM,\n",
|
| 156 |
+
" AutoTokenizer,\n",
|
| 157 |
+
" DataCollatorForLanguageModeling,\n",
|
| 158 |
+
" Trainer,\n",
|
| 159 |
+
" TrainingArguments,\n",
|
| 160 |
+
")\n",
|
| 161 |
+
"\n",
|
| 162 |
+
"from peft import CPTConfig, TaskType, get_peft_model\n",
|
| 163 |
+
"\n",
|
| 164 |
+
"\n",
|
| 165 |
+
"MAX_INPUT_LENGTH = 1024\n",
|
| 166 |
+
"MAX_ICL_SAMPLES = 10\n",
|
| 167 |
+
"NUM_TRAINING_SAMPLES = 100\n",
|
| 168 |
+
"model_id = 'bigscience/bloom-1b7'"
|
| 169 |
+
],
|
| 170 |
+
"metadata": {
|
| 171 |
+
"id": "Y0pETNFBl963"
|
| 172 |
+
},
|
| 173 |
+
"id": "Y0pETNFBl963",
|
| 174 |
+
"execution_count": 2,
|
| 175 |
+
"outputs": []
|
| 176 |
+
},
|
| 177 |
+
{
|
| 178 |
+
"cell_type": "markdown",
|
| 179 |
+
"source": [
|
| 180 |
+
"# Data Preparation\n",
|
| 181 |
+
"---"
|
| 182 |
+
],
|
| 183 |
+
"metadata": {
|
| 184 |
+
"id": "9hO_I3aDmCQu"
|
| 185 |
+
},
|
| 186 |
+
"id": "9hO_I3aDmCQu"
|
| 187 |
+
},
|
| 188 |
+
{
|
| 189 |
+
"cell_type": "code",
|
| 190 |
+
"source": [
|
| 191 |
+
"# Initialize the tokenizer\n",
|
| 192 |
+
"tokenizer = AutoTokenizer.from_pretrained(\n",
|
| 193 |
+
" model_id, # The name or path of the pre-trained tokenizer (e.g., \"bert-base-uncased\").\n",
|
| 194 |
+
" cache_dir='.', # Directory to cache the tokenizer files locally.\n",
|
| 195 |
+
" padding_side='right', # Specifies that padding should be added to the right side of sequences.\n",
|
| 196 |
+
" trust_remote_code=True # Allows loading tokenizer implementations from external sources.\n",
|
| 197 |
+
")"
|
| 198 |
+
],
|
| 199 |
+
"metadata": {
|
| 200 |
+
"id": "STK5N0LJrZmA",
|
| 201 |
+
"colab": {
|
| 202 |
+
"base_uri": "https://localhost:8080/"
|
| 203 |
+
},
|
| 204 |
+
"outputId": "4c5c3dda-07ae-4f67-df29-4a2ff499e5ad"
|
| 205 |
+
},
|
| 206 |
+
"id": "STK5N0LJrZmA",
|
| 207 |
+
"execution_count": 3,
|
| 208 |
+
"outputs": [
|
| 209 |
+
{
|
| 210 |
+
"output_type": "stream",
|
| 211 |
+
"name": "stderr",
|
| 212 |
+
"text": [
|
| 213 |
+
"/usr/local/lib/python3.10/dist-packages/huggingface_hub/utils/_auth.py:94: UserWarning: \n",
|
| 214 |
+
"The secret `HF_TOKEN` does not exist in your Colab secrets.\n",
|
| 215 |
+
"To authenticate with the Hugging Face Hub, create a token in your settings tab (https://huggingface.co/settings/tokens), set it as secret in your Google Colab and restart your session.\n",
|
| 216 |
+
"You will be able to reuse this secret in all of your notebooks.\n",
|
| 217 |
+
"Please note that authentication is recommended but still optional to access public models or datasets.\n",
|
| 218 |
+
" warnings.warn(\n"
|
| 219 |
+
]
|
| 220 |
+
}
|
| 221 |
+
]
|
| 222 |
+
},
|
| 223 |
+
{
|
| 224 |
+
"cell_type": "code",
|
| 225 |
+
"source": [
|
| 226 |
+
"# Load the SST-2 dataset from the GLUE benchmark\n",
|
| 227 |
+
"dataset = load_dataset('glue', 'sst2')\n",
|
| 228 |
+
"\n",
|
| 229 |
+
"def add_string_labels(example):\n",
|
| 230 |
+
" \"\"\"\n",
|
| 231 |
+
" Converts numerical labels into human-readable string labels.\n",
|
| 232 |
+
"\n",
|
| 233 |
+
" Args:\n",
|
| 234 |
+
" example (dict): A single example from the dataset with a numerical 'label'.\n",
|
| 235 |
+
"\n",
|
| 236 |
+
" Returns:\n",
|
| 237 |
+
" dict: The example augmented with a 'label_text' field.\n",
|
| 238 |
+
" \"\"\"\n",
|
| 239 |
+
" # Map numerical label to string label\n",
|
| 240 |
+
" example['label_text'] = \"positive\" if example['label'] == 1 else \"negative\"\n",
|
| 241 |
+
" return example\n",
|
| 242 |
+
"\n",
|
| 243 |
+
"# Subset and process the training dataset\n",
|
| 244 |
+
"context_dataset = dataset['train'].select(range(MAX_ICL_SAMPLES)).map(add_string_labels)\n",
|
| 245 |
+
"train_dataset = dataset['train'].select(range(MAX_ICL_SAMPLES, NUM_TRAINING_SAMPLES + MAX_ICL_SAMPLES)).map(add_string_labels)"
|
| 246 |
+
],
|
| 247 |
+
"metadata": {
|
| 248 |
+
"id": "C3oq4lDDrcUf",
|
| 249 |
+
"colab": {
|
| 250 |
+
"base_uri": "https://localhost:8080/",
|
| 251 |
+
"referenced_widgets": [
|
| 252 |
+
"72a5be4b77ec4d5994bcace9d462da84",
|
| 253 |
+
"bed78529ff2c4d08befca97c50cb5efc",
|
| 254 |
+
"cf7077acfce04aff8af0a2483dbf094c",
|
| 255 |
+
"910462d70d944d00ba54958d77bee755",
|
| 256 |
+
"a899818bdad0415b860eaac4afe31f30",
|
| 257 |
+
"3d78a6c8923547cf8c75bc8c10125eda",
|
| 258 |
+
"8083f95a673a423286ade63051de757d",
|
| 259 |
+
"13fc203ab1b44c83b6cfcc1e171d26ad",
|
| 260 |
+
"663a0196d2b547fd8a6890b8a86080c2",
|
| 261 |
+
"72be01164e974d59b05bee716e9bc978",
|
| 262 |
+
"4cedaf37e79e4ff1a10ffb96ec543e81"
|
| 263 |
+
],
|
| 264 |
+
"height": 49
|
| 265 |
+
},
|
| 266 |
+
"outputId": "5ae1ff54-d726-4f07-e6d7-cd53145b5d6f"
|
| 267 |
+
},
|
| 268 |
+
"id": "C3oq4lDDrcUf",
|
| 269 |
+
"execution_count": 4,
|
| 270 |
+
"outputs": [
|
| 271 |
+
{
|
| 272 |
+
"output_type": "display_data",
|
| 273 |
+
"data": {
|
| 274 |
+
"text/plain": [
|
| 275 |
+
"Map: 0%| | 0/100 [00:00<?, ? examples/s]"
|
| 276 |
+
],
|
| 277 |
+
"application/vnd.jupyter.widget-view+json": {
|
| 278 |
+
"version_major": 2,
|
| 279 |
+
"version_minor": 0,
|
| 280 |
+
"model_id": "72a5be4b77ec4d5994bcace9d462da84"
|
| 281 |
+
}
|
| 282 |
+
},
|
| 283 |
+
"metadata": {}
|
| 284 |
+
}
|
| 285 |
+
]
|
| 286 |
+
},
|
| 287 |
+
{
|
| 288 |
+
"cell_type": "markdown",
|
| 289 |
+
"source": [
|
| 290 |
+
"**Note:** This notebook uses small subsets of the dataset to ensure quick execution. For proper testing and evaluation, it is recommended to use the entire dataset by setting quick_review to False."
|
| 291 |
+
],
|
| 292 |
+
"metadata": {
|
| 293 |
+
"id": "ehlJCE80TnrC"
|
| 294 |
+
},
|
| 295 |
+
"id": "ehlJCE80TnrC"
|
| 296 |
+
},
|
| 297 |
+
{
|
| 298 |
+
"cell_type": "code",
|
| 299 |
+
"source": [
|
| 300 |
+
"quick_review = True # set to False for a comprehensive evaluation\n",
|
| 301 |
+
"num_of_test_examples = 100 if quick_review else len(dataset['validation'])\n",
|
| 302 |
+
"# Subset and process the validation dataset\n",
|
| 303 |
+
"test_dataset = dataset['validation'].select(range(num_of_test_examples)).map(add_string_labels)"
|
| 304 |
+
],
|
| 305 |
+
"metadata": {
|
| 306 |
+
"id": "yXoBN6EwTmNX"
|
| 307 |
+
},
|
| 308 |
+
"id": "yXoBN6EwTmNX",
|
| 309 |
+
"execution_count": 5,
|
| 310 |
+
"outputs": []
|
| 311 |
+
},
|
| 312 |
+
{
|
| 313 |
+
"cell_type": "markdown",
|
| 314 |
+
"source": [],
|
| 315 |
+
"metadata": {
|
| 316 |
+
"id": "YpXEWzglTl74"
|
| 317 |
+
},
|
| 318 |
+
"id": "YpXEWzglTl74"
|
| 319 |
+
},
|
| 320 |
+
{
|
| 321 |
+
"cell_type": "code",
|
| 322 |
+
"source": [
|
| 323 |
+
"class CPTDataset(Dataset):\n",
|
| 324 |
+
" def __init__(self, samples, tokenizer, template, max_length=MAX_INPUT_LENGTH):\n",
|
| 325 |
+
" \"\"\"\n",
|
| 326 |
+
" Initialize the CPTDataset with samples, a tokenizer, and a template.\n",
|
| 327 |
+
"\n",
|
| 328 |
+
" Args:\n",
|
| 329 |
+
" samples (list): List of samples containing input sentences and labels.\n",
|
| 330 |
+
" tokenizer: Tokenizer instance for encoding text.\n",
|
| 331 |
+
" template (dict): Dictionary defining input/output templates and separators.\n",
|
| 332 |
+
" max_length (int): Maximum input length for truncation.\n",
|
| 333 |
+
" \"\"\"\n",
|
| 334 |
+
" self.template = template\n",
|
| 335 |
+
" self.tokenizer = tokenizer\n",
|
| 336 |
+
" self.max_length = max_length\n",
|
| 337 |
+
"\n",
|
| 338 |
+
" # Storage for tokenized inputs and masks\n",
|
| 339 |
+
" self.attention_mask = []\n",
|
| 340 |
+
" self.input_ids = []\n",
|
| 341 |
+
" self.input_type_mask = []\n",
|
| 342 |
+
" self.inter_seperator_ids = self._get_input_ids(template['inter_seperator'])\n",
|
| 343 |
+
"\n",
|
| 344 |
+
" # Tokenize each sample and prepare inputs\n",
|
| 345 |
+
" for sample_i in tqdm(samples):\n",
|
| 346 |
+
" input_text, label = sample_i['sentence'], sample_i['label_text']\n",
|
| 347 |
+
" input_ids, attention_mask, input_type_mask = self.preprocess_sentence(input_text, label)\n",
|
| 348 |
+
"\n",
|
| 349 |
+
" self.input_ids.append(input_ids)\n",
|
| 350 |
+
" self.attention_mask.append(attention_mask)\n",
|
| 351 |
+
" self.input_type_mask.append(input_type_mask)\n",
|
| 352 |
+
"\n",
|
| 353 |
+
"\n",
|
| 354 |
+
" def _get_input_ids(self, text):\n",
|
| 355 |
+
" \"\"\"\n",
|
| 356 |
+
" Tokenize the given text into input IDs.\n",
|
| 357 |
+
"\n",
|
| 358 |
+
" Args:\n",
|
| 359 |
+
" text (str): The text to tokenize.\n",
|
| 360 |
+
"\n",
|
| 361 |
+
" Returns:\n",
|
| 362 |
+
" list: Tokenized input IDs.\n",
|
| 363 |
+
" \"\"\"\n",
|
| 364 |
+
" return self.tokenizer(text, add_special_tokens=False)[\"input_ids\"]\n",
|
| 365 |
+
"\n",
|
| 366 |
+
"\n",
|
| 367 |
+
" def preprocess_sentence(self, input_text, label):\n",
|
| 368 |
+
" \"\"\"\n",
|
| 369 |
+
" Preprocess a sentence and its corresponding label using templates.\n",
|
| 370 |
+
"\n",
|
| 371 |
+
" Args:\n",
|
| 372 |
+
" input_text (str): The input sentence.\n",
|
| 373 |
+
" label (str): The label text (e.g., \"positive\", \"negative\").\n",
|
| 374 |
+
"\n",
|
| 375 |
+
" Returns:\n",
|
| 376 |
+
" tuple: (input_ids, attention_mask, input_type_mask)\n",
|
| 377 |
+
" \"\"\"\n",
|
| 378 |
+
"\n",
|
| 379 |
+
" # Split input template into parts\n",
|
| 380 |
+
" input_template_part_1_text, input_template_part_2_text = self.template['input'].split('{}')\n",
|
| 381 |
+
" input_template_tokenized_part1 = self._get_input_ids(input_template_part_1_text)\n",
|
| 382 |
+
" input_tokenized = self._get_input_ids(input_text)\n",
|
| 383 |
+
" input_template_tokenized_part2 = self._get_input_ids(input_template_part_2_text)\n",
|
| 384 |
+
"\n",
|
| 385 |
+
" # Separator token\n",
|
| 386 |
+
" sep_tokenized = self._get_input_ids(self.template['intra_seperator'])\n",
|
| 387 |
+
"\n",
|
| 388 |
+
" # Process the label using the template\n",
|
| 389 |
+
" label_template_part_1, label_template_part_2 = self.template['output'].split('{}')\n",
|
| 390 |
+
" label_template_part1_tokenized = self._get_input_ids(label_template_part_1)\n",
|
| 391 |
+
" label_tokenized = self._get_input_ids(label)\n",
|
| 392 |
+
" label_template_part2_tokenized = self._get_input_ids(label_template_part_2)\n",
|
| 393 |
+
"\n",
|
| 394 |
+
" # End-of-sequence token\n",
|
| 395 |
+
" eos = [self.tokenizer.eos_token_id] if self.tokenizer.eos_token_id is not None else []\n",
|
| 396 |
+
"\n",
|
| 397 |
+
" # Concatenate all tokenized parts\n",
|
| 398 |
+
" input_ids = input_template_tokenized_part1 + input_tokenized + input_template_tokenized_part2 + sep_tokenized + label_template_part1_tokenized + label_tokenized + label_template_part2_tokenized + eos\n",
|
| 399 |
+
"\n",
|
| 400 |
+
" # Generate attention and type masks\n",
|
| 401 |
+
" attention_mask = [1] * len(input_ids)\n",
|
| 402 |
+
" input_type_mask = [1] * len(input_template_tokenized_part1) + [2] * len(input_tokenized) + [1] * len(\n",
|
| 403 |
+
" input_template_tokenized_part2) + [0] * len(sep_tokenized) + \\\n",
|
| 404 |
+
" [3] * len(label_template_part1_tokenized) + [4] * len(label_tokenized) + [3] * len( \\\n",
|
| 405 |
+
" label_template_part2_tokenized) + [0] * len(eos)\n",
|
| 406 |
+
"\n",
|
| 407 |
+
" # Ensure all masks and inputs are the same length\n",
|
| 408 |
+
" assert len(input_type_mask) == len(input_ids) == len(attention_mask)\n",
|
| 409 |
+
"\n",
|
| 410 |
+
" return input_ids, attention_mask, input_type_mask\n",
|
| 411 |
+
"\n",
|
| 412 |
+
"\n",
|
| 413 |
+
" def __len__(self):\n",
|
| 414 |
+
" \"\"\"\n",
|
| 415 |
+
" Get the number of examples in the dataset.\n",
|
| 416 |
+
"\n",
|
| 417 |
+
" Returns:\n",
|
| 418 |
+
" int: Number of examples.\n",
|
| 419 |
+
" \"\"\"\n",
|
| 420 |
+
" return len(self.input_ids)\n",
|
| 421 |
+
"\n",
|
| 422 |
+
"\n",
|
| 423 |
+
" def __getitem__(self, idx):\n",
|
| 424 |
+
" \"\"\"\n",
|
| 425 |
+
" Get the tokenized representation for the given index.\n",
|
| 426 |
+
"\n",
|
| 427 |
+
" Args:\n",
|
| 428 |
+
" idx (int): Index of the example.\n",
|
| 429 |
+
"\n",
|
| 430 |
+
" Returns:\n",
|
| 431 |
+
" dict: Tokenized inputs with attention and type masks.\n",
|
| 432 |
+
" \"\"\"\n",
|
| 433 |
+
"\n",
|
| 434 |
+
" return {\n",
|
| 435 |
+
" \"input_ids\": self.input_ids[idx],\n",
|
| 436 |
+
" \"attention_mask\": self.attention_mask[idx],\n",
|
| 437 |
+
" \"input_type_mask\": self.input_type_mask[idx]\n",
|
| 438 |
+
" }\n",
|
| 439 |
+
"\n",
|
| 440 |
+
"# Define templates for tokenization\n",
|
| 441 |
+
"templates = {\n",
|
| 442 |
+
" 'input': 'input: {}', # Input template with placeholder\n",
|
| 443 |
+
" 'intra_seperator': ' ', # Separator between input and output\n",
|
| 444 |
+
" 'output': 'output: {}', # Output template with placeholder\n",
|
| 445 |
+
" 'inter_seperator': '\\n' # Separator between examples\n",
|
| 446 |
+
"}\n",
|
| 447 |
+
"\n",
|
| 448 |
+
"# Initialize the dataset\n",
|
| 449 |
+
"cpt_train_dataset = CPTDataset(train_dataset, tokenizer, templates)\n",
|
| 450 |
+
"\n",
|
| 451 |
+
"\n",
|
| 452 |
+
"# - `templates`: Define how inputs and outputs should be formatted and separated.\n",
|
| 453 |
+
"# - `CPTDataset`: Converts the raw dataset into tokenized input IDs and masks."
|
| 454 |
+
],
|
| 455 |
+
"metadata": {
|
| 456 |
+
"colab": {
|
| 457 |
+
"base_uri": "https://localhost:8080/"
|
| 458 |
+
},
|
| 459 |
+
"id": "icJb6-Uqrf8p",
|
| 460 |
+
"outputId": "a0a2ddbc-1d1f-4845-93c9-19cf34b46024"
|
| 461 |
+
},
|
| 462 |
+
"id": "icJb6-Uqrf8p",
|
| 463 |
+
"execution_count": 6,
|
| 464 |
+
"outputs": [
|
| 465 |
+
{
|
| 466 |
+
"output_type": "stream",
|
| 467 |
+
"name": "stderr",
|
| 468 |
+
"text": [
|
| 469 |
+
"100%|██████████| 100/100 [00:00<00:00, 874.85it/s]\n"
|
| 470 |
+
]
|
| 471 |
+
}
|
| 472 |
+
]
|
| 473 |
+
},
|
| 474 |
+
{
|
| 475 |
+
"cell_type": "code",
|
| 476 |
+
"outputs": [
|
| 477 |
+
{
|
| 478 |
+
"output_type": "stream",
|
| 479 |
+
"name": "stderr",
|
| 480 |
+
"text": [
|
| 481 |
+
"100%|██████████| 10/10 [00:00<00:00, 1133.50it/s]\n"
|
| 482 |
+
]
|
| 483 |
+
}
|
| 484 |
+
],
|
| 485 |
+
"source": [
|
| 486 |
+
"# Initialize storage for context-level information\n",
|
| 487 |
+
"context_ids = [] # Concatenated input IDs for all samples\n",
|
| 488 |
+
"context_attention_mask = [] # Concatenated attention masks\n",
|
| 489 |
+
"context_input_type_mask = [] # Concatenated input type masks\n",
|
| 490 |
+
"first_type_mask = 0 # Initial offset for input type mask\n",
|
| 491 |
+
"\n",
|
| 492 |
+
"cpt_context_dataset = CPTDataset(context_dataset, tokenizer, templates)\n",
|
| 493 |
+
"\n",
|
| 494 |
+
"# Iterate through the CPT training dataset\n",
|
| 495 |
+
"for i in range(len(context_dataset)):\n",
|
| 496 |
+
" # Add input IDs to the context\n",
|
| 497 |
+
" context_ids += cpt_context_dataset[i]['input_ids']\n",
|
| 498 |
+
"\n",
|
| 499 |
+
" # Add attention mask to the context\n",
|
| 500 |
+
" context_attention_mask += cpt_context_dataset[i]['attention_mask']\n",
|
| 501 |
+
"\n",
|
| 502 |
+
" # Adjust and add the input type mask to the context\n",
|
| 503 |
+
" context_input_type_mask += [\n",
|
| 504 |
+
" i + first_type_mask if i > 0 else 0 # Increment type indices dynamically\n",
|
| 505 |
+
" for i in cpt_context_dataset[i]['input_type_mask']\n",
|
| 506 |
+
" ]\n",
|
| 507 |
+
"\n",
|
| 508 |
+
" # Increment the type mask offset after processing the sample\n",
|
| 509 |
+
" first_type_mask += 4"
|
| 510 |
+
],
|
| 511 |
+
"metadata": {
|
| 512 |
+
"ExecuteTime": {
|
| 513 |
+
"end_time": "2024-10-22T09:24:58.894814Z",
|
| 514 |
+
"start_time": "2024-10-22T09:24:58.893841Z"
|
| 515 |
+
},
|
| 516 |
+
"id": "aef03bbd5d86d3d8",
|
| 517 |
+
"colab": {
|
| 518 |
+
"base_uri": "https://localhost:8080/"
|
| 519 |
+
},
|
| 520 |
+
"outputId": "1bb1343b-b5f8-4998-e34b-6a8ae8063381"
|
| 521 |
+
},
|
| 522 |
+
"id": "aef03bbd5d86d3d8",
|
| 523 |
+
"execution_count": 7
|
| 524 |
+
},
|
| 525 |
+
{
|
| 526 |
+
"cell_type": "markdown",
|
| 527 |
+
"source": [
|
| 528 |
+
"# Model Training\n",
|
| 529 |
+
"\n",
|
| 530 |
+
"---"
|
| 531 |
+
],
|
| 532 |
+
"metadata": {
|
| 533 |
+
"collapsed": false,
|
| 534 |
+
"id": "2c40f24774d83372"
|
| 535 |
+
},
|
| 536 |
+
"id": "2c40f24774d83372"
|
| 537 |
+
},
|
| 538 |
+
{
|
| 539 |
+
"cell_type": "markdown",
|
| 540 |
+
"source": [
|
| 541 |
+
"## Load model"
|
| 542 |
+
],
|
| 543 |
+
"metadata": {
|
| 544 |
+
"id": "p0jFTzkisMgN"
|
| 545 |
+
},
|
| 546 |
+
"id": "p0jFTzkisMgN"
|
| 547 |
+
},
|
| 548 |
+
{
|
| 549 |
+
"cell_type": "code",
|
| 550 |
+
"outputs": [],
|
| 551 |
+
"source": [
|
| 552 |
+
"# Load a pre-trained causal language model\n",
|
| 553 |
+
"base_model = AutoModelForCausalLM.from_pretrained(\n",
|
| 554 |
+
" model_id,\n",
|
| 555 |
+
" cache_dir='.',\n",
|
| 556 |
+
" dtype=torch.float16,\n",
|
| 557 |
+
" device_map='auto'\n",
|
| 558 |
+
")\n",
|
| 559 |
+
"\n",
|
| 560 |
+
"# Initialize the CPT configuration\n",
|
| 561 |
+
"config = CPTConfig(\n",
|
| 562 |
+
" task_type=TaskType.CAUSAL_LM,\n",
|
| 563 |
+
" cpt_token_ids=context_ids,\n",
|
| 564 |
+
" cpt_mask=context_attention_mask,\n",
|
| 565 |
+
" cpt_tokens_type_mask=context_input_type_mask,\n",
|
| 566 |
+
"\n",
|
| 567 |
+
" opt_weighted_loss_type='decay',\n",
|
| 568 |
+
" opt_loss_decay_factor=0.95, # we choose the exponential decay factor applied to the loss\n",
|
| 569 |
+
" opt_projection_epsilon=0.2, # we choose the projection over the input tokens\n",
|
| 570 |
+
" opt_projection_format_epsilon=0.1, # we choose the projection over input and output templates\n",
|
| 571 |
+
"\n",
|
| 572 |
+
" tokenizer_name_or_path=model_id,\n",
|
| 573 |
+
")\n",
|
| 574 |
+
"\n",
|
| 575 |
+
"# Initialize the CPT model with PEFT\n",
|
| 576 |
+
"model = get_peft_model(base_model, config)"
|
| 577 |
+
],
|
| 578 |
+
"metadata": {
|
| 579 |
+
"ExecuteTime": {
|
| 580 |
+
"end_time": "2024-10-22T09:25:08.941945Z",
|
| 581 |
+
"start_time": "2024-10-22T09:25:04.393323Z"
|
| 582 |
+
},
|
| 583 |
+
"id": "17ac445134919a39"
|
| 584 |
+
},
|
| 585 |
+
"id": "17ac445134919a39",
|
| 586 |
+
"execution_count": 8
|
| 587 |
+
},
|
| 588 |
+
{
|
| 589 |
+
"cell_type": "markdown",
|
| 590 |
+
"source": [
|
| 591 |
+
"## Setting Collate Function"
|
| 592 |
+
],
|
| 593 |
+
"metadata": {
|
| 594 |
+
"collapsed": false,
|
| 595 |
+
"id": "4e49660c50d98741"
|
| 596 |
+
},
|
| 597 |
+
"id": "4e49660c50d98741"
|
| 598 |
+
},
|
| 599 |
+
{
|
| 600 |
+
"cell_type": "code",
|
| 601 |
+
"outputs": [],
|
| 602 |
+
"source": [
|
| 603 |
+
"class CPTDataCollatorForLanguageModeling(DataCollatorForLanguageModeling):\n",
|
| 604 |
+
" def __init__(self, tokenizer, training=True, mlm=False):\n",
|
| 605 |
+
" \"\"\"\n",
|
| 606 |
+
" Custom collator for CPT-style language modeling.\n",
|
| 607 |
+
"\n",
|
| 608 |
+
" Args:\n",
|
| 609 |
+
" tokenizer: The tokenizer to handle tokenization and special tokens.\n",
|
| 610 |
+
" training (bool): If True, operates in training mode; otherwise in evaluation mode.\n",
|
| 611 |
+
" mlm (bool): If True, enables masked language modeling.\n",
|
| 612 |
+
" \"\"\"\n",
|
| 613 |
+
"\n",
|
| 614 |
+
" super().__init__(tokenizer, mlm=mlm) # Initialize the parent class\n",
|
| 615 |
+
" self.training = training\n",
|
| 616 |
+
"\n",
|
| 617 |
+
" # Add a special padding token if not already defined\n",
|
| 618 |
+
" self.tokenizer.add_special_tokens({\"pad_token\": \"[PAD]\"})\n",
|
| 619 |
+
"\n",
|
| 620 |
+
" def torch_call(self, examples: List[Union[List[int], Any, Dict[str, Any]]]) -> Dict[str, Any]:\n",
|
| 621 |
+
" \"\"\"\n",
|
| 622 |
+
" Process a batch of examples for language modeling.\n",
|
| 623 |
+
"\n",
|
| 624 |
+
" Args:\n",
|
| 625 |
+
" examples (List): A batch of examples with tokenized inputs and optional sample masks.\n",
|
| 626 |
+
"\n",
|
| 627 |
+
" Returns:\n",
|
| 628 |
+
" Dict: A dictionary containing padded and tensor-converted inputs, attention masks,\n",
|
| 629 |
+
" input type masks, and optional sample masks and labels.\n",
|
| 630 |
+
" \"\"\"\n",
|
| 631 |
+
"\n",
|
| 632 |
+
" # Initialize a list to collect sample masks if provided\n",
|
| 633 |
+
" list_sample_mask = []\n",
|
| 634 |
+
" for i in range(len(examples)):\n",
|
| 635 |
+
" if \"sample_mask\" in examples[i].keys():\n",
|
| 636 |
+
" list_sample_mask.append(examples[i].pop(\"sample_mask\"))\n",
|
| 637 |
+
"\n",
|
| 638 |
+
" # Define a helper function for padding sequences to the maximum length\n",
|
| 639 |
+
" max_len = max(len(ex[\"input_ids\"]) for ex in examples)\n",
|
| 640 |
+
"\n",
|
| 641 |
+
" # Define a helper function for padding sequences to the maximum length\n",
|
| 642 |
+
" def pad_sequence(sequence, max_len, pad_value=0):\n",
|
| 643 |
+
" return sequence + [pad_value] * (max_len - len(sequence))\n",
|
| 644 |
+
"\n",
|
| 645 |
+
" # Pad and convert `input_ids`, `attention_mask`, and `input_type_mask` to tensors\n",
|
| 646 |
+
" input_ids = torch.tensor([pad_sequence(ex[\"input_ids\"], max_len) for ex in examples])\n",
|
| 647 |
+
" attention_mask = torch.tensor([pad_sequence(ex[\"attention_mask\"], max_len) for ex in examples])\n",
|
| 648 |
+
" input_type_mask = torch.tensor([pad_sequence(ex[\"input_type_mask\"], max_len) for ex in examples])\n",
|
| 649 |
+
"\n",
|
| 650 |
+
" # Create the initial batch dictionary\n",
|
| 651 |
+
" batch = {\"input_ids\": input_ids, \"attention_mask\": attention_mask, \"input_type_mask\": input_type_mask}\n",
|
| 652 |
+
"\n",
|
| 653 |
+
" # Create a tensor to store sample masks\n",
|
| 654 |
+
" tensor_sample_mask = batch[\"input_ids\"].clone().long()\n",
|
| 655 |
+
" tensor_sample_mask[:, :] = 0 # Initialize with zeros\n",
|
| 656 |
+
"\n",
|
| 657 |
+
" # Populate the tensor with the provided sample masks\n",
|
| 658 |
+
" for i in range(len(list_sample_mask)):\n",
|
| 659 |
+
" tensor_sample_mask[i, : len(list_sample_mask[i])] = list_sample_mask[i]\n",
|
| 660 |
+
"\n",
|
| 661 |
+
" # Copy `input_ids` to use as `labels`\n",
|
| 662 |
+
" batch[\"labels\"] = batch[\"input_ids\"].clone()\n",
|
| 663 |
+
"\n",
|
| 664 |
+
" # If in evaluation mode, include the `sample_mask` in the batch\n",
|
| 665 |
+
" if not self.training:\n",
|
| 666 |
+
" batch[\"sample_mask\"] = tensor_sample_mask\n",
|
| 667 |
+
"\n",
|
| 668 |
+
" return batch"
|
| 669 |
+
],
|
| 670 |
+
"metadata": {
|
| 671 |
+
"ExecuteTime": {
|
| 672 |
+
"end_time": "2024-10-22T09:25:08.953199Z",
|
| 673 |
+
"start_time": "2024-10-22T09:25:08.945689Z"
|
| 674 |
+
},
|
| 675 |
+
"id": "b0fac840f060e3aa"
|
| 676 |
+
},
|
| 677 |
+
"id": "b0fac840f060e3aa",
|
| 678 |
+
"execution_count": 9
|
| 679 |
+
},
|
| 680 |
+
{
|
| 681 |
+
"cell_type": "markdown",
|
| 682 |
+
"source": [
|
| 683 |
+
"## Training"
|
| 684 |
+
],
|
| 685 |
+
"metadata": {
|
| 686 |
+
"collapsed": false,
|
| 687 |
+
"id": "48f535d74e6602b"
|
| 688 |
+
},
|
| 689 |
+
"id": "48f535d74e6602b"
|
| 690 |
+
},
|
| 691 |
+
{
|
| 692 |
+
"cell_type": "code",
|
| 693 |
+
"outputs": [
|
| 694 |
+
{
|
| 695 |
+
"output_type": "display_data",
|
| 696 |
+
"data": {
|
| 697 |
+
"text/plain": [
|
| 698 |
+
"<IPython.core.display.HTML object>"
|
| 699 |
+
],
|
| 700 |
+
"text/html": [
|
| 701 |
+
"\n",
|
| 702 |
+
" <div>\n",
|
| 703 |
+
" \n",
|
| 704 |
+
" <progress value='500' max='500' style='width:300px; height:20px; vertical-align: middle;'></progress>\n",
|
| 705 |
+
" [500/500 01:28, Epoch 5/5]\n",
|
| 706 |
+
" </div>\n",
|
| 707 |
+
" <table border=\"1\" class=\"dataframe\">\n",
|
| 708 |
+
" <thead>\n",
|
| 709 |
+
" <tr style=\"text-align: left;\">\n",
|
| 710 |
+
" <th>Step</th>\n",
|
| 711 |
+
" <th>Training Loss</th>\n",
|
| 712 |
+
" </tr>\n",
|
| 713 |
+
" </thead>\n",
|
| 714 |
+
" <tbody>\n",
|
| 715 |
+
" <tr>\n",
|
| 716 |
+
" <td>100</td>\n",
|
| 717 |
+
" <td>0.400800</td>\n",
|
| 718 |
+
" </tr>\n",
|
| 719 |
+
" <tr>\n",
|
| 720 |
+
" <td>200</td>\n",
|
| 721 |
+
" <td>0.036000</td>\n",
|
| 722 |
+
" </tr>\n",
|
| 723 |
+
" <tr>\n",
|
| 724 |
+
" <td>300</td>\n",
|
| 725 |
+
" <td>0.026300</td>\n",
|
| 726 |
+
" </tr>\n",
|
| 727 |
+
" <tr>\n",
|
| 728 |
+
" <td>400</td>\n",
|
| 729 |
+
" <td>0.016100</td>\n",
|
| 730 |
+
" </tr>\n",
|
| 731 |
+
" <tr>\n",
|
| 732 |
+
" <td>500</td>\n",
|
| 733 |
+
" <td>0.011600</td>\n",
|
| 734 |
+
" </tr>\n",
|
| 735 |
+
" </tbody>\n",
|
| 736 |
+
"</table><p>"
|
| 737 |
+
]
|
| 738 |
+
},
|
| 739 |
+
"metadata": {}
|
| 740 |
+
},
|
| 741 |
+
{
|
| 742 |
+
"output_type": "execute_result",
|
| 743 |
+
"data": {
|
| 744 |
+
"text/plain": [
|
| 745 |
+
"TrainOutput(global_step=500, training_loss=0.09815525007247924, metrics={'train_runtime': 90.6767, 'train_samples_per_second': 5.514, 'train_steps_per_second': 5.514, 'total_flos': 79477977907200.0, 'train_loss': 0.09815525007247924, 'epoch': 5.0})"
|
| 746 |
+
]
|
| 747 |
+
},
|
| 748 |
+
"metadata": {},
|
| 749 |
+
"execution_count": 10
|
| 750 |
+
}
|
| 751 |
+
],
|
| 752 |
+
"source": [
|
| 753 |
+
"training_args = TrainingArguments(\n",
|
| 754 |
+
" output_dir='../.',\n",
|
| 755 |
+
" use_cpu=False,\n",
|
| 756 |
+
" auto_find_batch_size=False,\n",
|
| 757 |
+
" learning_rate=1e-4,\n",
|
| 758 |
+
" logging_steps=100,\n",
|
| 759 |
+
" per_device_train_batch_size=1,\n",
|
| 760 |
+
" save_total_limit=1,\n",
|
| 761 |
+
" remove_unused_columns=False,\n",
|
| 762 |
+
" num_train_epochs=5,\n",
|
| 763 |
+
" fp16=True,\n",
|
| 764 |
+
" save_strategy='no',\n",
|
| 765 |
+
" report_to=\"none\"\n",
|
| 766 |
+
")\n",
|
| 767 |
+
"\n",
|
| 768 |
+
"trainer = Trainer(\n",
|
| 769 |
+
" model=model,\n",
|
| 770 |
+
" args=training_args,\n",
|
| 771 |
+
" train_dataset=cpt_train_dataset, # Custom CPT training dataset.\n",
|
| 772 |
+
" data_collator=CPTDataCollatorForLanguageModeling(tokenizer, training=True, mlm=False)\n",
|
| 773 |
+
")\n",
|
| 774 |
+
"\n",
|
| 775 |
+
"trainer.train()"
|
| 776 |
+
],
|
| 777 |
+
"metadata": {
|
| 778 |
+
"ExecuteTime": {
|
| 779 |
+
"end_time": "2024-10-22T09:25:27.599132Z",
|
| 780 |
+
"start_time": "2024-10-22T09:25:13.906685Z"
|
| 781 |
+
},
|
| 782 |
+
"colab": {
|
| 783 |
+
"base_uri": "https://localhost:8080/",
|
| 784 |
+
"height": 268
|
| 785 |
+
},
|
| 786 |
+
"id": "1a865c2ad2dc7218",
|
| 787 |
+
"outputId": "c4bfd785-e354-4ee6-a87e-63c17bfd2605"
|
| 788 |
+
},
|
| 789 |
+
"id": "1a865c2ad2dc7218",
|
| 790 |
+
"execution_count": 10
|
| 791 |
+
},
|
| 792 |
+
{
|
| 793 |
+
"cell_type": "markdown",
|
| 794 |
+
"source": [
|
| 795 |
+
"# Model Evaluation\n",
|
| 796 |
+
"\n",
|
| 797 |
+
"---"
|
| 798 |
+
],
|
| 799 |
+
"metadata": {
|
| 800 |
+
"collapsed": false,
|
| 801 |
+
"id": "b799ea89a567590f"
|
| 802 |
+
},
|
| 803 |
+
"id": "b799ea89a567590f"
|
| 804 |
+
},
|
| 805 |
+
{
|
| 806 |
+
"cell_type": "code",
|
| 807 |
+
"outputs": [
|
| 808 |
+
{
|
| 809 |
+
"output_type": "stream",
|
| 810 |
+
"name": "stderr",
|
| 811 |
+
"text": [
|
| 812 |
+
"100%|██████████| 100/100 [00:00<00:00, 1972.82it/s]\n"
|
| 813 |
+
]
|
| 814 |
+
},
|
| 815 |
+
{
|
| 816 |
+
"output_type": "stream",
|
| 817 |
+
"name": "stdout",
|
| 818 |
+
"text": [
|
| 819 |
+
"Sentence: input: it 's a charming and often affecting journey . output: positive</s> \n",
|
| 820 |
+
" \t The prediction is: positive\n",
|
| 821 |
+
" \t The GT is positive\n",
|
| 822 |
+
"Sentence: input: unflinchingly bleak and desperate output: negative</s> \n",
|
| 823 |
+
" \t The prediction is: negative\n",
|
| 824 |
+
" \t The GT is negative\n",
|
| 825 |
+
"Sentence: input: allows us to hope that nolan is poised to embark a major career as a commercial yet inventive filmmaker . output: positive</s> \n",
|
| 826 |
+
" \t The prediction is: positive\n",
|
| 827 |
+
" \t The GT is positive\n",
|
| 828 |
+
"Sentence: input: the acting , costumes , music , cinematography and sound are all astounding given the production 's austere locales . output: positive</s> \n",
|
| 829 |
+
" \t The prediction is: positive\n",
|
| 830 |
+
" \t The GT is positive\n",
|
| 831 |
+
"Sentence: input: it 's slow -- very , very slow . output: negative</s> \n",
|
| 832 |
+
" \t The prediction is: negative\n",
|
| 833 |
+
" \t The GT is negative\n",
|
| 834 |
+
"Sentence: input: although laced with humor and a few fanciful touches , the film is a refreshingly serious look at young women . output: positive</s> \n",
|
| 835 |
+
" \t The prediction is: positive\n",
|
| 836 |
+
" \t The GT is positive\n",
|
| 837 |
+
"Sentence: input: a sometimes tedious film . output: negative</s> \n",
|
| 838 |
+
" \t The prediction is: negative\n",
|
| 839 |
+
" \t The GT is negative\n",
|
| 840 |
+
"Sentence: input: or doing last year 's taxes with your ex-wife . output: negative</s> \n",
|
| 841 |
+
" \t The prediction is: negative\n",
|
| 842 |
+
" \t The GT is negative\n",
|
| 843 |
+
"Sentence: input: you do n't have to know about music to appreciate the film 's easygoing blend of comedy and romance . output: positive</s> \n",
|
| 844 |
+
" \t The prediction is: positive\n",
|
| 845 |
+
" \t The GT is positive\n",
|
| 846 |
+
"Sentence: input: in exactly 89 minutes , most of which passed as slowly as if i 'd been sitting naked on an igloo , formula 51 sank from quirky to jerky to utter turkey . output: negative</s> \n",
|
| 847 |
+
" \t The prediction is: negative\n",
|
| 848 |
+
" \t The GT is negative\n",
|
| 849 |
+
"Sentence: input: the mesmerizing performances of the leads keep the film grounded and keep the audience riveted . output: positive</s> \n",
|
| 850 |
+
" \t The prediction is: positive\n",
|
| 851 |
+
" \t The GT is positive\n",
|
| 852 |
+
"Sentence: input: it takes a strange kind of laziness to waste the talents of robert forster , anne meara , eugene levy , and reginald veljohnson all in the same movie . output: negative</s> \n",
|
| 853 |
+
" \t The prediction is: negative\n",
|
| 854 |
+
" \t The GT is negative\n",
|
| 855 |
+
"Sentence: input: ... the film suffers from a lack of humor ( something needed to balance out the violence ) ... output: negative</s> \n",
|
| 856 |
+
" \t The prediction is: negative\n",
|
| 857 |
+
" \t The GT is negative\n",
|
| 858 |
+
"Sentence: input: we root for ( clara and paul ) , even like them , though perhaps it 's an emotion closer to pity . output: positive</s> \n",
|
| 859 |
+
" \t The prediction is: positive\n",
|
| 860 |
+
" \t The GT is positive\n",
|
| 861 |
+
"Sentence: input: even horror fans will most likely not find what they 're seeking with trouble every day ; the movie lacks both thrills and humor . output: negative</s> \n",
|
| 862 |
+
" \t The prediction is: negative\n",
|
| 863 |
+
" \t The GT is negative\n",
|
| 864 |
+
"Sentence: input: a gorgeous , high-spirited musical from india that exquisitely blends music , dance , song , and high drama . output: positive</s> \n",
|
| 865 |
+
" \t The prediction is: positive\n",
|
| 866 |
+
" \t The GT is positive\n",
|
| 867 |
+
"Sentence: input: the emotions are raw and will strike a nerve with anyone who 's ever had family trauma . output: positive</s> \n",
|
| 868 |
+
" \t The prediction is: positive\n",
|
| 869 |
+
" \t The GT is positive\n",
|
| 870 |
+
"Sentence: input: audrey tatou has a knack for picking roles that magnify her outrageous charm , and in this literate french comedy , she 's as morning-glory exuberant as she was in amélie . output: positive</s> \n",
|
| 871 |
+
" \t The prediction is: positive\n",
|
| 872 |
+
" \t The GT is positive\n",
|
| 873 |
+
"Sentence: input: ... the movie is just a plain old monster . output: negative</s> \n",
|
| 874 |
+
" \t The prediction is: negative\n",
|
| 875 |
+
" \t The GT is negative\n",
|
| 876 |
+
"Sentence: input: in its best moments , resembles a bad high school production of grease , without benefit of song . output: negative</s> \n",
|
| 877 |
+
" \t The prediction is: negative\n",
|
| 878 |
+
" \t The GT is negative\n",
|
| 879 |
+
"Sentence: input: pumpkin takes an admirable look at the hypocrisy of political correctness , but it does so with such an uneven tone that you never know when humor ends and tragedy begins . output: negative</s> \n",
|
| 880 |
+
" \t The prediction is: negative\n",
|
| 881 |
+
" \t The GT is negative\n",
|
| 882 |
+
"Sentence: input: the iditarod lasts for days - this just felt like it did . output: negative</s> \n",
|
| 883 |
+
" \t The prediction is: negative\n",
|
| 884 |
+
" \t The GT is negative\n",
|
| 885 |
+
"Sentence: input: holden caulfield did it better . output: negative</s> \n",
|
| 886 |
+
" \t The prediction is: positive\n",
|
| 887 |
+
" \t The GT is negative\n",
|
| 888 |
+
"Sentence: input: a delectable and intriguing thriller filled with surprises , read my lips is an original . output: positive</s> \n",
|
| 889 |
+
" \t The prediction is: positive\n",
|
| 890 |
+
" \t The GT is positive\n",
|
| 891 |
+
"Sentence: input: seldom has a movie so closely matched the spirit of a man and his work . output: positive</s> \n",
|
| 892 |
+
" \t The prediction is: positive\n",
|
| 893 |
+
" \t The GT is positive\n",
|
| 894 |
+
"Sentence: input: nicks , seemingly uncertain what 's going to make people laugh , runs the gamut from stale parody to raunchy sex gags to formula romantic comedy . output: negative</s> \n",
|
| 895 |
+
" \t The prediction is: negative\n",
|
| 896 |
+
" \t The GT is negative\n",
|
| 897 |
+
"Sentence: input: the action switches between past and present , but the material link is too tenuous to anchor the emotional connections that purport to span a 125-year divide . output: negative</s> \n",
|
| 898 |
+
" \t The prediction is: negative\n",
|
| 899 |
+
" \t The GT is negative\n",
|
| 900 |
+
"Sentence: input: it 's an offbeat treat that pokes fun at the democratic exercise while also examining its significance for those who take part . output: positive</s> \n",
|
| 901 |
+
" \t The prediction is: positive\n",
|
| 902 |
+
" \t The GT is positive\n",
|
| 903 |
+
"Sentence: input: it 's a cookie-cutter movie , a cut-and-paste job . output: negative</s> \n",
|
| 904 |
+
" \t The prediction is: negative\n",
|
| 905 |
+
" \t The GT is negative\n",
|
| 906 |
+
"Sentence: input: i had to look away - this was god awful . output: negative</s> \n",
|
| 907 |
+
" \t The prediction is: negative\n",
|
| 908 |
+
" \t The GT is negative\n",
|
| 909 |
+
"Sentence: input: thanks to scott 's charismatic roger and eisenberg 's sweet nephew , roger dodger is one of the most compelling variations on in the company of men . output: positive</s> \n",
|
| 910 |
+
" \t The prediction is: positive\n",
|
| 911 |
+
" \t The GT is positive\n",
|
| 912 |
+
"Sentence: input: ... designed to provide a mix of smiles and tears , `` crossroads '' instead provokes a handful of unintentional howlers and numerous yawns . output: negative</s> \n",
|
| 913 |
+
" \t The prediction is: negative\n",
|
| 914 |
+
" \t The GT is negative\n",
|
| 915 |
+
"Sentence: input: a gorgeous , witty , seductive movie . output: positive</s> \n",
|
| 916 |
+
" \t The prediction is: positive\n",
|
| 917 |
+
" \t The GT is positive\n",
|
| 918 |
+
"Sentence: input: if the movie succeeds in instilling a wary sense of ` there but for the grace of god , ' it is far too self-conscious to draw you deeply into its world . output: negative</s> \n",
|
| 919 |
+
" \t The prediction is: negative\n",
|
| 920 |
+
" \t The GT is negative\n",
|
| 921 |
+
"Sentence: input: it does n't believe in itself , it has no sense of humor ... it 's just plain bored . output: negative</s> \n",
|
| 922 |
+
" \t The prediction is: negative\n",
|
| 923 |
+
" \t The GT is negative\n",
|
| 924 |
+
"Sentence: input: a sequence of ridiculous shoot - 'em - up scenes . output: negative</s> \n",
|
| 925 |
+
" \t The prediction is: negative\n",
|
| 926 |
+
" \t The GT is negative\n",
|
| 927 |
+
"Sentence: input: the weight of the piece , the unerring professionalism of the chilly production , and the fascination embedded in the lurid topic prove recommendation enough . output: positive</s> \n",
|
| 928 |
+
" \t The prediction is: positive\n",
|
| 929 |
+
" \t The GT is positive\n",
|
| 930 |
+
"Sentence: input: ( w ) hile long on amiable monkeys and worthy environmentalism , jane goodall 's wild chimpanzees is short on the thrills the oversize medium demands . output: negative</s> \n",
|
| 931 |
+
" \t The prediction is: negative\n",
|
| 932 |
+
" \t The GT is negative\n",
|
| 933 |
+
"Sentence: input: as surreal as a dream and as detailed as a photograph , as visually dexterous as it is at times imaginatively overwhelming . output: positive</s> \n",
|
| 934 |
+
" \t The prediction is: positive\n",
|
| 935 |
+
" \t The GT is positive\n",
|
| 936 |
+
"Sentence: input: escaping the studio , piccoli is warmly affecting and so is this adroitly minimalist movie . output: positive</s> \n",
|
| 937 |
+
" \t The prediction is: positive\n",
|
| 938 |
+
" \t The GT is positive\n",
|
| 939 |
+
"Sentence: input: there 's ... tremendous energy from the cast , a sense of playfulness and excitement that seems appropriate . output: positive</s> \n",
|
| 940 |
+
" \t The prediction is: positive\n",
|
| 941 |
+
" \t The GT is positive\n",
|
| 942 |
+
"Sentence: input: this illuminating documentary transcends our preconceived vision of the holy land and its inhabitants , revealing the human complexities beneath . output: positive</s> \n",
|
| 943 |
+
" \t The prediction is: positive\n",
|
| 944 |
+
" \t The GT is positive\n",
|
| 945 |
+
"Sentence: input: the subtle strength of `` elling '' is that it never loses touch with the reality of the grim situation . output: positive</s> \n",
|
| 946 |
+
" \t The prediction is: positive\n",
|
| 947 |
+
" \t The GT is positive\n",
|
| 948 |
+
"Sentence: input: holm ... embodies the character with an effortlessly regal charisma . output: positive</s> \n",
|
| 949 |
+
" \t The prediction is: positive\n",
|
| 950 |
+
" \t The GT is positive\n",
|
| 951 |
+
"Sentence: input: the title not only describes its main characters , but the lazy people behind the camera as well . output: negative</s> \n",
|
| 952 |
+
" \t The prediction is: positive\n",
|
| 953 |
+
" \t The GT is negative\n",
|
| 954 |
+
"Sentence: input: it offers little beyond the momentary joys of pretty and weightless intellectual entertainment . output: negative</s> \n",
|
| 955 |
+
" \t The prediction is: positive\n",
|
| 956 |
+
" \t The GT is negative\n",
|
| 957 |
+
"Sentence: input: a synthesis of cliches and absurdities that seems positively decadent in its cinematic flash and emptiness . output: negative</s> \n",
|
| 958 |
+
" \t The prediction is: negative\n",
|
| 959 |
+
" \t The GT is negative\n",
|
| 960 |
+
"Sentence: input: a subtle and well-crafted ( for the most part ) chiller . output: positive</s> \n",
|
| 961 |
+
" \t The prediction is: positive\n",
|
| 962 |
+
" \t The GT is positive\n",
|
| 963 |
+
"Sentence: input: has a lot of the virtues of eastwood at his best . output: positive</s> \n",
|
| 964 |
+
" \t The prediction is: positive\n",
|
| 965 |
+
" \t The GT is positive\n",
|
| 966 |
+
"Sentence: input: it 's hampered by a lifetime-channel kind of plot and a lead actress who is out of her depth . output: negative</s> \n",
|
| 967 |
+
" \t The prediction is: negative\n",
|
| 968 |
+
" \t The GT is negative\n",
|
| 969 |
+
"Sentence: input: it feels like an after-school special gussied up with some fancy special effects , and watching its rote plot points connect is about as exciting as gazing at an egg timer for 93 minutes . output: negative</s> \n",
|
| 970 |
+
" \t The prediction is: positive\n",
|
| 971 |
+
" \t The GT is negative\n",
|
| 972 |
+
"Sentence: input: for the most part , director anne-sophie birot 's first feature is a sensitive , extraordinarily well-acted drama . output: positive</s> \n",
|
| 973 |
+
" \t The prediction is: positive\n",
|
| 974 |
+
" \t The GT is positive\n",
|
| 975 |
+
"Sentence: input: mr. tsai is a very original artist in his medium , and what time is it there ? output: positive</s> \n",
|
| 976 |
+
" \t The prediction is: positive\n",
|
| 977 |
+
" \t The GT is positive\n",
|
| 978 |
+
"Sentence: input: sade is an engaging look at the controversial eponymous and fiercely atheistic hero . output: positive</s> \n",
|
| 979 |
+
" \t The prediction is: positive\n",
|
| 980 |
+
" \t The GT is positive\n",
|
| 981 |
+
"Sentence: input: so devoid of any kind of intelligible story that it makes films like xxx and collateral damage seem like thoughtful treatises output: negative</s> \n",
|
| 982 |
+
" \t The prediction is: negative\n",
|
| 983 |
+
" \t The GT is negative\n",
|
| 984 |
+
"Sentence: input: a tender , heartfelt family drama . output: positive</s> \n",
|
| 985 |
+
" \t The prediction is: positive\n",
|
| 986 |
+
" \t The GT is positive\n",
|
| 987 |
+
"Sentence: input: ... a hollow joke told by a cinematic gymnast having too much fun embellishing the misanthropic tale to actually engage it . output: negative</s> \n",
|
| 988 |
+
" \t The prediction is: negative\n",
|
| 989 |
+
" \t The GT is negative\n",
|
| 990 |
+
"Sentence: input: the cold turkey would 've been a far better title . output: negative</s> \n",
|
| 991 |
+
" \t The prediction is: negative\n",
|
| 992 |
+
" \t The GT is negative\n",
|
| 993 |
+
"Sentence: input: manages to be both repulsively sadistic and mundane . output: negative</s> \n",
|
| 994 |
+
" \t The prediction is: negative\n",
|
| 995 |
+
" \t The GT is negative\n",
|
| 996 |
+
"Sentence: input: it 's just disappointingly superficial -- a movie that has all the elements necessary to be a fascinating , involving character study , but never does more than scratch the surface . output: negative</s> \n",
|
| 997 |
+
" \t The prediction is: negative\n",
|
| 998 |
+
" \t The GT is negative\n",
|
| 999 |
+
"Sentence: input: this is a story of two misfits who do n't stand a chance alone , but together they are magnificent . output: positive</s> \n",
|
| 1000 |
+
" \t The prediction is: positive\n",
|
| 1001 |
+
" \t The GT is positive\n",
|
| 1002 |
+
"Sentence: input: schaeffer has to find some hook on which to hang his persistently useless movies , and it might as well be the resuscitation of the middle-aged character . output: negative</s> \n",
|
| 1003 |
+
" \t The prediction is: negative\n",
|
| 1004 |
+
" \t The GT is negative\n",
|
| 1005 |
+
"Sentence: input: the primitive force of this film seems to bubble up from the vast collective memory of the combatants . output: positive</s> \n",
|
| 1006 |
+
" \t The prediction is: positive\n",
|
| 1007 |
+
" \t The GT is positive\n",
|
| 1008 |
+
"Sentence: input: on this tricky topic , tadpole is very much a step in the right direction , with its blend of frankness , civility and compassion . output: positive</s> \n",
|
| 1009 |
+
" \t The prediction is: positive\n",
|
| 1010 |
+
" \t The GT is positive\n",
|
| 1011 |
+
"Sentence: input: the script kicks in , and mr. hartley 's distended pace and foot-dragging rhythms follow . output: negative</s> \n",
|
| 1012 |
+
" \t The prediction is: positive\n",
|
| 1013 |
+
" \t The GT is negative\n",
|
| 1014 |
+
"Sentence: input: you wonder why enough was n't just a music video rather than a full-length movie . output: negative</s> \n",
|
| 1015 |
+
" \t The prediction is: negative\n",
|
| 1016 |
+
" \t The GT is negative\n",
|
| 1017 |
+
"Sentence: input: if you 're hard up for raunchy college humor , this is your ticket right here . output: positive</s> \n",
|
| 1018 |
+
" \t The prediction is: positive\n",
|
| 1019 |
+
" \t The GT is positive\n",
|
| 1020 |
+
"Sentence: input: a fast , funny , highly enjoyable movie . output: positive</s> \n",
|
| 1021 |
+
" \t The prediction is: positive\n",
|
| 1022 |
+
" \t The GT is positive\n",
|
| 1023 |
+
"Sentence: input: good old-fashioned slash-and-hack is back ! output: positive</s> \n",
|
| 1024 |
+
" \t The prediction is: positive\n",
|
| 1025 |
+
" \t The GT is positive\n",
|
| 1026 |
+
"Sentence: input: this one is definitely one to skip , even for horror movie fanatics . output: negative</s> \n",
|
| 1027 |
+
" \t The prediction is: negative\n",
|
| 1028 |
+
" \t The GT is negative\n",
|
| 1029 |
+
"Sentence: input: for all its impressive craftsmanship , and despite an overbearing series of third-act crescendos , lily chou-chou never really builds up a head of emotional steam . output: negative</s> \n",
|
| 1030 |
+
" \t The prediction is: negative\n",
|
| 1031 |
+
" \t The GT is negative\n",
|
| 1032 |
+
"Sentence: input: exquisitely nuanced in mood tics and dialogue , this chamber drama is superbly acted by the deeply appealing veteran bouquet and the chilling but quite human berling . output: positive</s> \n",
|
| 1033 |
+
" \t The prediction is: positive\n",
|
| 1034 |
+
" \t The GT is positive\n",
|
| 1035 |
+
"Sentence: input: uses high comedy to evoke surprising poignance . output: positive</s> \n",
|
| 1036 |
+
" \t The prediction is: positive\n",
|
| 1037 |
+
" \t The GT is positive\n",
|
| 1038 |
+
"Sentence: input: one of creepiest , scariest movies to come along in a long , long time , easily rivaling blair witch or the others . output: positive</s> \n",
|
| 1039 |
+
" \t The prediction is: positive\n",
|
| 1040 |
+
" \t The GT is positive\n",
|
| 1041 |
+
"Sentence: input: a string of rehashed sight gags based in insipid vulgarity . output: negative</s> \n",
|
| 1042 |
+
" \t The prediction is: negative\n",
|
| 1043 |
+
" \t The GT is negative\n",
|
| 1044 |
+
"Sentence: input: among the year 's most intriguing explorations of alientation . output: positive</s> \n",
|
| 1045 |
+
" \t The prediction is: positive\n",
|
| 1046 |
+
" \t The GT is positive\n",
|
| 1047 |
+
"Sentence: input: the movie fails to live up to the sum of its parts . output: negative</s> \n",
|
| 1048 |
+
" \t The prediction is: negative\n",
|
| 1049 |
+
" \t The GT is negative\n",
|
| 1050 |
+
"Sentence: input: the son 's room is a triumph of gentility that earns its moments of pathos . output: positive</s> \n",
|
| 1051 |
+
" \t The prediction is: positive\n",
|
| 1052 |
+
" \t The GT is positive\n",
|
| 1053 |
+
"Sentence: input: there is nothing outstanding about this film , but it is good enough and will likely be appreciated most by sailors and folks who know their way around a submarine . output: positive</s> \n",
|
| 1054 |
+
" \t The prediction is: positive\n",
|
| 1055 |
+
" \t The GT is positive\n",
|
| 1056 |
+
"Sentence: input: this is a train wreck of an action film -- a stupefying attempt by the filmmakers to force-feed james bond into the mindless xxx mold and throw 40 years of cinematic history down the toilet in favor of bright flashes and loud bangs . output: negative</s> \n",
|
| 1057 |
+
" \t The prediction is: negative\n",
|
| 1058 |
+
" \t The GT is negative\n",
|
| 1059 |
+
"Sentence: input: the draw ( for `` big bad love '' ) is a solid performance by arliss howard . output: positive</s> \n",
|
| 1060 |
+
" \t The prediction is: positive\n",
|
| 1061 |
+
" \t The GT is positive\n",
|
| 1062 |
+
"Sentence: input: green might want to hang onto that ski mask , as robbery may be the only way to pay for his next project . output: negative</s> \n",
|
| 1063 |
+
" \t The prediction is: positive\n",
|
| 1064 |
+
" \t The GT is negative\n",
|
| 1065 |
+
"Sentence: input: it 's one pussy-ass world when even killer-thrillers revolve around group therapy sessions . output: negative</s> \n",
|
| 1066 |
+
" \t The prediction is: negative\n",
|
| 1067 |
+
" \t The GT is negative\n",
|
| 1068 |
+
"Sentence: input: though it 's become almost redundant to say so , major kudos go to leigh for actually casting people who look working-class . output: positive</s> \n",
|
| 1069 |
+
" \t The prediction is: positive\n",
|
| 1070 |
+
" \t The GT is positive\n",
|
| 1071 |
+
"Sentence: input: the band 's courage in the face of official repression is inspiring , especially for aging hippies ( this one included ) . output: positive</s> \n",
|
| 1072 |
+
" \t The prediction is: positive\n",
|
| 1073 |
+
" \t The GT is positive\n",
|
| 1074 |
+
"Sentence: input: the movie achieves as great an impact by keeping these thoughts hidden as ... ( quills ) did by showing them . output: positive</s> \n",
|
| 1075 |
+
" \t The prediction is: positive\n",
|
| 1076 |
+
" \t The GT is positive\n",
|
| 1077 |
+
"Sentence: input: the film flat lines when it should peak and is more missed opportunity and trifle than dark , decadent truffle . output: negative</s> \n",
|
| 1078 |
+
" \t The prediction is: negative\n",
|
| 1079 |
+
" \t The GT is negative\n",
|
| 1080 |
+
"Sentence: input: jaglom ... put ( s ) the audience in the privileged position of eavesdropping on his characters output: positive</s> \n",
|
| 1081 |
+
" \t The prediction is: positive\n",
|
| 1082 |
+
" \t The GT is positive\n",
|
| 1083 |
+
"Sentence: input: fresnadillo 's dark and jolting images have a way of plying into your subconscious like the nightmare you had a week ago that wo n't go away . output: positive</s> \n",
|
| 1084 |
+
" \t The prediction is: positive\n",
|
| 1085 |
+
" \t The GT is positive\n",
|
| 1086 |
+
"Sentence: input: we know the plot 's a little crazy , but it held my interest from start to finish . output: positive</s> \n",
|
| 1087 |
+
" \t The prediction is: positive\n",
|
| 1088 |
+
" \t The GT is positive\n",
|
| 1089 |
+
"Sentence: input: it 's a scattershot affair , but when it hits its mark it 's brilliant . output: positive</s> \n",
|
| 1090 |
+
" \t The prediction is: positive\n",
|
| 1091 |
+
" \t The GT is positive\n",
|
| 1092 |
+
"Sentence: input: hardly a masterpiece , but it introduces viewers to a good charitable enterprise and some interesting real people . output: positive</s> \n",
|
| 1093 |
+
" \t The prediction is: positive\n",
|
| 1094 |
+
" \t The GT is positive\n",
|
| 1095 |
+
"Sentence: input: you wo n't like roger , but you will quickly recognize him . output: negative</s> \n",
|
| 1096 |
+
" \t The prediction is: positive\n",
|
| 1097 |
+
" \t The GT is negative\n",
|
| 1098 |
+
"Sentence: input: if steven soderbergh 's ` solaris ' is a failure it is a glorious failure . output: positive</s> \n",
|
| 1099 |
+
" \t The prediction is: negative\n",
|
| 1100 |
+
" \t The GT is positive\n",
|
| 1101 |
+
"Sentence: input: byler reveals his characters in a way that intrigues and even fascinates us , and he never reduces the situation to simple melodrama . output: positive</s> \n",
|
| 1102 |
+
" \t The prediction is: positive\n",
|
| 1103 |
+
" \t The GT is positive\n",
|
| 1104 |
+
"Sentence: input: this riveting world war ii moral suspense story deals with the shadow side of american culture : racial prejudice in its ugly and diverse forms . output: negative</s> \n",
|
| 1105 |
+
" \t The prediction is: positive\n",
|
| 1106 |
+
" \t The GT is negative\n",
|
| 1107 |
+
"Sentence: input: it 's difficult to imagine the process that produced such a script , but here 's guessing that spray cheese and underarm noises played a crucial role . output: negative</s> \n",
|
| 1108 |
+
" \t The prediction is: positive\n",
|
| 1109 |
+
" \t The GT is negative\n",
|
| 1110 |
+
"Sentence: input: no sophomore slump for director sam mendes , who segues from oscar winner to oscar-winning potential with a smooth sleight of hand . output: positive</s> \n",
|
| 1111 |
+
" \t The prediction is: positive\n",
|
| 1112 |
+
" \t The GT is positive\n",
|
| 1113 |
+
"Sentence: input: on the whole , the movie lacks wit , feeling and believability to compensate for its incessant coarseness and banality . output: negative</s> \n",
|
| 1114 |
+
" \t The prediction is: negative\n",
|
| 1115 |
+
" \t The GT is negative\n",
|
| 1116 |
+
"Sentence: input: why make a documentary about these marginal historical figures ? output: negative</s> \n",
|
| 1117 |
+
" \t The prediction is: negative\n",
|
| 1118 |
+
" \t The GT is negative\n",
|
| 1119 |
+
"The model Acc is 90.0%\n"
|
| 1120 |
+
]
|
| 1121 |
+
}
|
| 1122 |
+
],
|
| 1123 |
+
"source": [
|
| 1124 |
+
"model.eval()\n",
|
| 1125 |
+
"\n",
|
| 1126 |
+
"# Select relevant columns from the test dataset\n",
|
| 1127 |
+
"test_dataset = test_dataset.select_columns(['sentence', 'label_text'])\n",
|
| 1128 |
+
"\n",
|
| 1129 |
+
"# Convert the test dataset to a CPT-compatible format\n",
|
| 1130 |
+
"cpt_test_dataset = CPTDataset(test_dataset, tokenizer, templates)\n",
|
| 1131 |
+
"\n",
|
| 1132 |
+
"# Get the device where the model is loaded (CPU, GPU or XPU)\n",
|
| 1133 |
+
"device = model.device\n",
|
| 1134 |
+
"list_bool_predictions = []\n",
|
| 1135 |
+
"\n",
|
| 1136 |
+
"for i in range(len(test_dataset)):\n",
|
| 1137 |
+
" input_ids, input_type_mask = cpt_test_dataset[i]['input_ids'], cpt_test_dataset[i]['input_type_mask']\n",
|
| 1138 |
+
"\n",
|
| 1139 |
+
" # Pass the inputs through the model\n",
|
| 1140 |
+
" outputs = model(\n",
|
| 1141 |
+
" input_ids=torch.Tensor(input_ids).long().to(device=device).view(1, -1),\n",
|
| 1142 |
+
" labels=torch.Tensor(input_ids).long().to(device=device).view(1, -1),\n",
|
| 1143 |
+
" input_type_mask=torch.Tensor(input_type_mask).long().to(device=device).view(1, -1)\n",
|
| 1144 |
+
" )\n",
|
| 1145 |
+
"\n",
|
| 1146 |
+
" # Shift logits to exclude the last token and match the labels\n",
|
| 1147 |
+
" shifted_logits = outputs.logits[..., :-1, :].contiguous().to(model.dtype)[0, -len(input_ids) + 1:]\n",
|
| 1148 |
+
" shift_labels = torch.Tensor(input_ids).long().to(device=device).view(1, -1)[0, 1:].contiguous().to(device)\n",
|
| 1149 |
+
" shifted_input_type_mask = torch.Tensor(input_type_mask).long().to(device=device).view(1, -1)[..., 1:].contiguous().to(device)\n",
|
| 1150 |
+
"\n",
|
| 1151 |
+
" # Create a mask for the type `4` tokens (label tokens)\n",
|
| 1152 |
+
" mask = torch.Tensor(shifted_input_type_mask).long().to(device=device).view(-1,) == 4\n",
|
| 1153 |
+
"\n",
|
| 1154 |
+
" # Extract logits and labels corresponding to the mask\n",
|
| 1155 |
+
" logit = shifted_logits[mask]\n",
|
| 1156 |
+
" label = shift_labels[mask]\n",
|
| 1157 |
+
"\n",
|
| 1158 |
+
" # All possible label tokens for `negative` and `positive`\n",
|
| 1159 |
+
" all_labels = torch.Tensor([tokenizer(i, add_special_tokens=False)[\"input_ids\"] for i in ['negative', 'positive']]).long().to(device).view(-1,)\n",
|
| 1160 |
+
"\n",
|
| 1161 |
+
" # Compare logits with label tokens and infer prediction\n",
|
| 1162 |
+
" prediction = logit[0, torch.Tensor([tokenizer(i, add_special_tokens=False)[\"input_ids\"] for i in ['negative', 'positive']]).long().to(device).view(-1,)].argmax()\n",
|
| 1163 |
+
" prediction_text = 'negative' if prediction == 0 else 'positive'\n",
|
| 1164 |
+
" print(f\"Sentence: {tokenizer.decode(input_ids)} \\n \\t The prediction is: {prediction_text}\\n \\t The GT is {tokenizer.decode(label)}\")\n",
|
| 1165 |
+
" list_bool_predictions.append(prediction_text == tokenizer.decode(label))\n",
|
| 1166 |
+
"\n",
|
| 1167 |
+
"print(f'The model Acc is {100 * np.mean(list_bool_predictions)}%')"
|
| 1168 |
+
],
|
| 1169 |
+
"metadata": {
|
| 1170 |
+
"ExecuteTime": {
|
| 1171 |
+
"end_time": "2024-10-22T09:25:28.252009Z",
|
| 1172 |
+
"start_time": "2024-10-22T09:25:27.598326Z"
|
| 1173 |
+
},
|
| 1174 |
+
"id": "48e7d976e6e01212",
|
| 1175 |
+
"colab": {
|
| 1176 |
+
"base_uri": "https://localhost:8080/"
|
| 1177 |
+
},
|
| 1178 |
+
"outputId": "40dd1226-fa31-4e77-dc7e-e06a3600304e"
|
| 1179 |
+
},
|
| 1180 |
+
"id": "48e7d976e6e01212",
|
| 1181 |
+
"execution_count": 11
|
| 1182 |
+
}
|
| 1183 |
+
],
|
| 1184 |
+
"metadata": {
|
| 1185 |
+
"kernelspec": {
|
| 1186 |
+
"display_name": "Python 3",
|
| 1187 |
+
"name": "python3"
|
| 1188 |
+
},
|
| 1189 |
+
"language_info": {
|
| 1190 |
+
"codemirror_mode": {
|
| 1191 |
+
"name": "ipython",
|
| 1192 |
+
"version": 2
|
| 1193 |
+
},
|
| 1194 |
+
"file_extension": ".py",
|
| 1195 |
+
"mimetype": "text/x-python",
|
| 1196 |
+
"name": "python",
|
| 1197 |
+
"nbconvert_exporter": "python",
|
| 1198 |
+
"pygments_lexer": "ipython2",
|
| 1199 |
+
"version": "2.7.6"
|
| 1200 |
+
},
|
| 1201 |
+
"colab": {
|
| 1202 |
+
"provenance": [],
|
| 1203 |
+
"gpuType": "T4"
|
| 1204 |
+
},
|
| 1205 |
+
"accelerator": "GPU",
|
| 1206 |
+
"widgets": {
|
| 1207 |
+
"application/vnd.jupyter.widget-state+json": {
|
| 1208 |
+
"72a5be4b77ec4d5994bcace9d462da84": {
|
| 1209 |
+
"model_module": "@jupyter-widgets/controls",
|
| 1210 |
+
"model_name": "HBoxModel",
|
| 1211 |
+
"model_module_version": "1.5.0",
|
| 1212 |
+
"state": {
|
| 1213 |
+
"_dom_classes": [],
|
| 1214 |
+
"_model_module": "@jupyter-widgets/controls",
|
| 1215 |
+
"_model_module_version": "1.5.0",
|
| 1216 |
+
"_model_name": "HBoxModel",
|
| 1217 |
+
"_view_count": null,
|
| 1218 |
+
"_view_module": "@jupyter-widgets/controls",
|
| 1219 |
+
"_view_module_version": "1.5.0",
|
| 1220 |
+
"_view_name": "HBoxView",
|
| 1221 |
+
"box_style": "",
|
| 1222 |
+
"children": [
|
| 1223 |
+
"IPY_MODEL_bed78529ff2c4d08befca97c50cb5efc",
|
| 1224 |
+
"IPY_MODEL_cf7077acfce04aff8af0a2483dbf094c",
|
| 1225 |
+
"IPY_MODEL_910462d70d944d00ba54958d77bee755"
|
| 1226 |
+
],
|
| 1227 |
+
"layout": "IPY_MODEL_a899818bdad0415b860eaac4afe31f30"
|
| 1228 |
+
}
|
| 1229 |
+
},
|
| 1230 |
+
"bed78529ff2c4d08befca97c50cb5efc": {
|
| 1231 |
+
"model_module": "@jupyter-widgets/controls",
|
| 1232 |
+
"model_name": "HTMLModel",
|
| 1233 |
+
"model_module_version": "1.5.0",
|
| 1234 |
+
"state": {
|
| 1235 |
+
"_dom_classes": [],
|
| 1236 |
+
"_model_module": "@jupyter-widgets/controls",
|
| 1237 |
+
"_model_module_version": "1.5.0",
|
| 1238 |
+
"_model_name": "HTMLModel",
|
| 1239 |
+
"_view_count": null,
|
| 1240 |
+
"_view_module": "@jupyter-widgets/controls",
|
| 1241 |
+
"_view_module_version": "1.5.0",
|
| 1242 |
+
"_view_name": "HTMLView",
|
| 1243 |
+
"description": "",
|
| 1244 |
+
"description_tooltip": null,
|
| 1245 |
+
"layout": "IPY_MODEL_3d78a6c8923547cf8c75bc8c10125eda",
|
| 1246 |
+
"placeholder": "",
|
| 1247 |
+
"style": "IPY_MODEL_8083f95a673a423286ade63051de757d",
|
| 1248 |
+
"value": "Map: 100%"
|
| 1249 |
+
}
|
| 1250 |
+
},
|
| 1251 |
+
"cf7077acfce04aff8af0a2483dbf094c": {
|
| 1252 |
+
"model_module": "@jupyter-widgets/controls",
|
| 1253 |
+
"model_name": "FloatProgressModel",
|
| 1254 |
+
"model_module_version": "1.5.0",
|
| 1255 |
+
"state": {
|
| 1256 |
+
"_dom_classes": [],
|
| 1257 |
+
"_model_module": "@jupyter-widgets/controls",
|
| 1258 |
+
"_model_module_version": "1.5.0",
|
| 1259 |
+
"_model_name": "FloatProgressModel",
|
| 1260 |
+
"_view_count": null,
|
| 1261 |
+
"_view_module": "@jupyter-widgets/controls",
|
| 1262 |
+
"_view_module_version": "1.5.0",
|
| 1263 |
+
"_view_name": "ProgressView",
|
| 1264 |
+
"bar_style": "success",
|
| 1265 |
+
"description": "",
|
| 1266 |
+
"description_tooltip": null,
|
| 1267 |
+
"layout": "IPY_MODEL_13fc203ab1b44c83b6cfcc1e171d26ad",
|
| 1268 |
+
"max": 100,
|
| 1269 |
+
"min": 0,
|
| 1270 |
+
"orientation": "horizontal",
|
| 1271 |
+
"style": "IPY_MODEL_663a0196d2b547fd8a6890b8a86080c2",
|
| 1272 |
+
"value": 100
|
| 1273 |
+
}
|
| 1274 |
+
},
|
| 1275 |
+
"910462d70d944d00ba54958d77bee755": {
|
| 1276 |
+
"model_module": "@jupyter-widgets/controls",
|
| 1277 |
+
"model_name": "HTMLModel",
|
| 1278 |
+
"model_module_version": "1.5.0",
|
| 1279 |
+
"state": {
|
| 1280 |
+
"_dom_classes": [],
|
| 1281 |
+
"_model_module": "@jupyter-widgets/controls",
|
| 1282 |
+
"_model_module_version": "1.5.0",
|
| 1283 |
+
"_model_name": "HTMLModel",
|
| 1284 |
+
"_view_count": null,
|
| 1285 |
+
"_view_module": "@jupyter-widgets/controls",
|
| 1286 |
+
"_view_module_version": "1.5.0",
|
| 1287 |
+
"_view_name": "HTMLView",
|
| 1288 |
+
"description": "",
|
| 1289 |
+
"description_tooltip": null,
|
| 1290 |
+
"layout": "IPY_MODEL_72be01164e974d59b05bee716e9bc978",
|
| 1291 |
+
"placeholder": "",
|
| 1292 |
+
"style": "IPY_MODEL_4cedaf37e79e4ff1a10ffb96ec543e81",
|
| 1293 |
+
"value": " 100/100 [00:00<00:00, 1327.06 examples/s]"
|
| 1294 |
+
}
|
| 1295 |
+
},
|
| 1296 |
+
"a899818bdad0415b860eaac4afe31f30": {
|
| 1297 |
+
"model_module": "@jupyter-widgets/base",
|
| 1298 |
+
"model_name": "LayoutModel",
|
| 1299 |
+
"model_module_version": "1.2.0",
|
| 1300 |
+
"state": {
|
| 1301 |
+
"_model_module": "@jupyter-widgets/base",
|
| 1302 |
+
"_model_module_version": "1.2.0",
|
| 1303 |
+
"_model_name": "LayoutModel",
|
| 1304 |
+
"_view_count": null,
|
| 1305 |
+
"_view_module": "@jupyter-widgets/base",
|
| 1306 |
+
"_view_module_version": "1.2.0",
|
| 1307 |
+
"_view_name": "LayoutView",
|
| 1308 |
+
"align_content": null,
|
| 1309 |
+
"align_items": null,
|
| 1310 |
+
"align_self": null,
|
| 1311 |
+
"border": null,
|
| 1312 |
+
"bottom": null,
|
| 1313 |
+
"display": null,
|
| 1314 |
+
"flex": null,
|
| 1315 |
+
"flex_flow": null,
|
| 1316 |
+
"grid_area": null,
|
| 1317 |
+
"grid_auto_columns": null,
|
| 1318 |
+
"grid_auto_flow": null,
|
| 1319 |
+
"grid_auto_rows": null,
|
| 1320 |
+
"grid_column": null,
|
| 1321 |
+
"grid_gap": null,
|
| 1322 |
+
"grid_row": null,
|
| 1323 |
+
"grid_template_areas": null,
|
| 1324 |
+
"grid_template_columns": null,
|
| 1325 |
+
"grid_template_rows": null,
|
| 1326 |
+
"height": null,
|
| 1327 |
+
"justify_content": null,
|
| 1328 |
+
"justify_items": null,
|
| 1329 |
+
"left": null,
|
| 1330 |
+
"margin": null,
|
| 1331 |
+
"max_height": null,
|
| 1332 |
+
"max_width": null,
|
| 1333 |
+
"min_height": null,
|
| 1334 |
+
"min_width": null,
|
| 1335 |
+
"object_fit": null,
|
| 1336 |
+
"object_position": null,
|
| 1337 |
+
"order": null,
|
| 1338 |
+
"overflow": null,
|
| 1339 |
+
"overflow_x": null,
|
| 1340 |
+
"overflow_y": null,
|
| 1341 |
+
"padding": null,
|
| 1342 |
+
"right": null,
|
| 1343 |
+
"top": null,
|
| 1344 |
+
"visibility": null,
|
| 1345 |
+
"width": null
|
| 1346 |
+
}
|
| 1347 |
+
},
|
| 1348 |
+
"3d78a6c8923547cf8c75bc8c10125eda": {
|
| 1349 |
+
"model_module": "@jupyter-widgets/base",
|
| 1350 |
+
"model_name": "LayoutModel",
|
| 1351 |
+
"model_module_version": "1.2.0",
|
| 1352 |
+
"state": {
|
| 1353 |
+
"_model_module": "@jupyter-widgets/base",
|
| 1354 |
+
"_model_module_version": "1.2.0",
|
| 1355 |
+
"_model_name": "LayoutModel",
|
| 1356 |
+
"_view_count": null,
|
| 1357 |
+
"_view_module": "@jupyter-widgets/base",
|
| 1358 |
+
"_view_module_version": "1.2.0",
|
| 1359 |
+
"_view_name": "LayoutView",
|
| 1360 |
+
"align_content": null,
|
| 1361 |
+
"align_items": null,
|
| 1362 |
+
"align_self": null,
|
| 1363 |
+
"border": null,
|
| 1364 |
+
"bottom": null,
|
| 1365 |
+
"display": null,
|
| 1366 |
+
"flex": null,
|
| 1367 |
+
"flex_flow": null,
|
| 1368 |
+
"grid_area": null,
|
| 1369 |
+
"grid_auto_columns": null,
|
| 1370 |
+
"grid_auto_flow": null,
|
| 1371 |
+
"grid_auto_rows": null,
|
| 1372 |
+
"grid_column": null,
|
| 1373 |
+
"grid_gap": null,
|
| 1374 |
+
"grid_row": null,
|
| 1375 |
+
"grid_template_areas": null,
|
| 1376 |
+
"grid_template_columns": null,
|
| 1377 |
+
"grid_template_rows": null,
|
| 1378 |
+
"height": null,
|
| 1379 |
+
"justify_content": null,
|
| 1380 |
+
"justify_items": null,
|
| 1381 |
+
"left": null,
|
| 1382 |
+
"margin": null,
|
| 1383 |
+
"max_height": null,
|
| 1384 |
+
"max_width": null,
|
| 1385 |
+
"min_height": null,
|
| 1386 |
+
"min_width": null,
|
| 1387 |
+
"object_fit": null,
|
| 1388 |
+
"object_position": null,
|
| 1389 |
+
"order": null,
|
| 1390 |
+
"overflow": null,
|
| 1391 |
+
"overflow_x": null,
|
| 1392 |
+
"overflow_y": null,
|
| 1393 |
+
"padding": null,
|
| 1394 |
+
"right": null,
|
| 1395 |
+
"top": null,
|
| 1396 |
+
"visibility": null,
|
| 1397 |
+
"width": null
|
| 1398 |
+
}
|
| 1399 |
+
},
|
| 1400 |
+
"8083f95a673a423286ade63051de757d": {
|
| 1401 |
+
"model_module": "@jupyter-widgets/controls",
|
| 1402 |
+
"model_name": "DescriptionStyleModel",
|
| 1403 |
+
"model_module_version": "1.5.0",
|
| 1404 |
+
"state": {
|
| 1405 |
+
"_model_module": "@jupyter-widgets/controls",
|
| 1406 |
+
"_model_module_version": "1.5.0",
|
| 1407 |
+
"_model_name": "DescriptionStyleModel",
|
| 1408 |
+
"_view_count": null,
|
| 1409 |
+
"_view_module": "@jupyter-widgets/base",
|
| 1410 |
+
"_view_module_version": "1.2.0",
|
| 1411 |
+
"_view_name": "StyleView",
|
| 1412 |
+
"description_width": ""
|
| 1413 |
+
}
|
| 1414 |
+
},
|
| 1415 |
+
"13fc203ab1b44c83b6cfcc1e171d26ad": {
|
| 1416 |
+
"model_module": "@jupyter-widgets/base",
|
| 1417 |
+
"model_name": "LayoutModel",
|
| 1418 |
+
"model_module_version": "1.2.0",
|
| 1419 |
+
"state": {
|
| 1420 |
+
"_model_module": "@jupyter-widgets/base",
|
| 1421 |
+
"_model_module_version": "1.2.0",
|
| 1422 |
+
"_model_name": "LayoutModel",
|
| 1423 |
+
"_view_count": null,
|
| 1424 |
+
"_view_module": "@jupyter-widgets/base",
|
| 1425 |
+
"_view_module_version": "1.2.0",
|
| 1426 |
+
"_view_name": "LayoutView",
|
| 1427 |
+
"align_content": null,
|
| 1428 |
+
"align_items": null,
|
| 1429 |
+
"align_self": null,
|
| 1430 |
+
"border": null,
|
| 1431 |
+
"bottom": null,
|
| 1432 |
+
"display": null,
|
| 1433 |
+
"flex": null,
|
| 1434 |
+
"flex_flow": null,
|
| 1435 |
+
"grid_area": null,
|
| 1436 |
+
"grid_auto_columns": null,
|
| 1437 |
+
"grid_auto_flow": null,
|
| 1438 |
+
"grid_auto_rows": null,
|
| 1439 |
+
"grid_column": null,
|
| 1440 |
+
"grid_gap": null,
|
| 1441 |
+
"grid_row": null,
|
| 1442 |
+
"grid_template_areas": null,
|
| 1443 |
+
"grid_template_columns": null,
|
| 1444 |
+
"grid_template_rows": null,
|
| 1445 |
+
"height": null,
|
| 1446 |
+
"justify_content": null,
|
| 1447 |
+
"justify_items": null,
|
| 1448 |
+
"left": null,
|
| 1449 |
+
"margin": null,
|
| 1450 |
+
"max_height": null,
|
| 1451 |
+
"max_width": null,
|
| 1452 |
+
"min_height": null,
|
| 1453 |
+
"min_width": null,
|
| 1454 |
+
"object_fit": null,
|
| 1455 |
+
"object_position": null,
|
| 1456 |
+
"order": null,
|
| 1457 |
+
"overflow": null,
|
| 1458 |
+
"overflow_x": null,
|
| 1459 |
+
"overflow_y": null,
|
| 1460 |
+
"padding": null,
|
| 1461 |
+
"right": null,
|
| 1462 |
+
"top": null,
|
| 1463 |
+
"visibility": null,
|
| 1464 |
+
"width": null
|
| 1465 |
+
}
|
| 1466 |
+
},
|
| 1467 |
+
"663a0196d2b547fd8a6890b8a86080c2": {
|
| 1468 |
+
"model_module": "@jupyter-widgets/controls",
|
| 1469 |
+
"model_name": "ProgressStyleModel",
|
| 1470 |
+
"model_module_version": "1.5.0",
|
| 1471 |
+
"state": {
|
| 1472 |
+
"_model_module": "@jupyter-widgets/controls",
|
| 1473 |
+
"_model_module_version": "1.5.0",
|
| 1474 |
+
"_model_name": "ProgressStyleModel",
|
| 1475 |
+
"_view_count": null,
|
| 1476 |
+
"_view_module": "@jupyter-widgets/base",
|
| 1477 |
+
"_view_module_version": "1.2.0",
|
| 1478 |
+
"_view_name": "StyleView",
|
| 1479 |
+
"bar_color": null,
|
| 1480 |
+
"description_width": ""
|
| 1481 |
+
}
|
| 1482 |
+
},
|
| 1483 |
+
"72be01164e974d59b05bee716e9bc978": {
|
| 1484 |
+
"model_module": "@jupyter-widgets/base",
|
| 1485 |
+
"model_name": "LayoutModel",
|
| 1486 |
+
"model_module_version": "1.2.0",
|
| 1487 |
+
"state": {
|
| 1488 |
+
"_model_module": "@jupyter-widgets/base",
|
| 1489 |
+
"_model_module_version": "1.2.0",
|
| 1490 |
+
"_model_name": "LayoutModel",
|
| 1491 |
+
"_view_count": null,
|
| 1492 |
+
"_view_module": "@jupyter-widgets/base",
|
| 1493 |
+
"_view_module_version": "1.2.0",
|
| 1494 |
+
"_view_name": "LayoutView",
|
| 1495 |
+
"align_content": null,
|
| 1496 |
+
"align_items": null,
|
| 1497 |
+
"align_self": null,
|
| 1498 |
+
"border": null,
|
| 1499 |
+
"bottom": null,
|
| 1500 |
+
"display": null,
|
| 1501 |
+
"flex": null,
|
| 1502 |
+
"flex_flow": null,
|
| 1503 |
+
"grid_area": null,
|
| 1504 |
+
"grid_auto_columns": null,
|
| 1505 |
+
"grid_auto_flow": null,
|
| 1506 |
+
"grid_auto_rows": null,
|
| 1507 |
+
"grid_column": null,
|
| 1508 |
+
"grid_gap": null,
|
| 1509 |
+
"grid_row": null,
|
| 1510 |
+
"grid_template_areas": null,
|
| 1511 |
+
"grid_template_columns": null,
|
| 1512 |
+
"grid_template_rows": null,
|
| 1513 |
+
"height": null,
|
| 1514 |
+
"justify_content": null,
|
| 1515 |
+
"justify_items": null,
|
| 1516 |
+
"left": null,
|
| 1517 |
+
"margin": null,
|
| 1518 |
+
"max_height": null,
|
| 1519 |
+
"max_width": null,
|
| 1520 |
+
"min_height": null,
|
| 1521 |
+
"min_width": null,
|
| 1522 |
+
"object_fit": null,
|
| 1523 |
+
"object_position": null,
|
| 1524 |
+
"order": null,
|
| 1525 |
+
"overflow": null,
|
| 1526 |
+
"overflow_x": null,
|
| 1527 |
+
"overflow_y": null,
|
| 1528 |
+
"padding": null,
|
| 1529 |
+
"right": null,
|
| 1530 |
+
"top": null,
|
| 1531 |
+
"visibility": null,
|
| 1532 |
+
"width": null
|
| 1533 |
+
}
|
| 1534 |
+
},
|
| 1535 |
+
"4cedaf37e79e4ff1a10ffb96ec543e81": {
|
| 1536 |
+
"model_module": "@jupyter-widgets/controls",
|
| 1537 |
+
"model_name": "DescriptionStyleModel",
|
| 1538 |
+
"model_module_version": "1.5.0",
|
| 1539 |
+
"state": {
|
| 1540 |
+
"_model_module": "@jupyter-widgets/controls",
|
| 1541 |
+
"_model_module_version": "1.5.0",
|
| 1542 |
+
"_model_name": "DescriptionStyleModel",
|
| 1543 |
+
"_view_count": null,
|
| 1544 |
+
"_view_module": "@jupyter-widgets/base",
|
| 1545 |
+
"_view_module_version": "1.2.0",
|
| 1546 |
+
"_view_name": "StyleView",
|
| 1547 |
+
"description_width": ""
|
| 1548 |
+
}
|
| 1549 |
+
}
|
| 1550 |
+
}
|
| 1551 |
+
}
|
| 1552 |
+
},
|
| 1553 |
+
"nbformat": 4,
|
| 1554 |
+
"nbformat_minor": 5
|
| 1555 |
+
}
|
tasks/tasksmith-ecb1931929df/tests/source/examples/delora_finetuning/README.md
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# DeLoRA: Decoupled Low-Rank Adaptation
|
| 2 |
+
|
| 3 |
+
## Introduction
|
| 4 |
+
[DeLoRA](https://huggingface.co/papers/2503.18225) tackles finetuning in a Frobenius-norm bounded setup: this allows to prevent divergence from the pretrained model, effectively decoupling the learning of angles and magnitudes.
|
| 5 |
+
|
| 6 |
+
This is done by (i) normalization of the BA low-rank matrices, which bound the updates' Frobenius norm, (ii) learnable scaling lambda, which controls the update's boundary/magnitude, (iii) layer-wise scaling of ||W||, to adapt each update's norm to the original weights' norm.
|
| 7 |
+
|
| 8 |
+
## Quick start
|
| 9 |
+
|
| 10 |
+
With respect to your standard PEFT training procedure with LoRA, simply swap your `LoraConfig` for a `DeloraConfig`. Note however that `lora_alpha` parameter is replaced by `delora_lambda` parameter which sets an upper bound to the Frobenius norm of the weight change.
|
| 11 |
+
|
| 12 |
+
```python
|
| 13 |
+
import torch
|
| 14 |
+
from peft import DeloraConfig, get_peft_model
|
| 15 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 16 |
+
from trl import SFTConfig, SFTTrainer
|
| 17 |
+
from datasets import load_dataset
|
| 18 |
+
|
| 19 |
+
model = AutoModelForCausalLM.from_pretrained("meta-llama/Meta-Llama-3-8B", dtype=torch.bfloat16, device_map="auto")
|
| 20 |
+
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3-8B")
|
| 21 |
+
tokenizer.pad_token_id = tokenizer.eos_token_id
|
| 22 |
+
delora_config = DeloraConfig(r=32, delora_lambda=15)
|
| 23 |
+
|
| 24 |
+
peft_model = get_peft_model(model, delora_config)
|
| 25 |
+
peft_model.print_trainable_parameters()
|
| 26 |
+
|
| 27 |
+
dataset = load_dataset("imdb", split="train[:1%]")
|
| 28 |
+
|
| 29 |
+
training_args = SFTConfig(dataset_text_field="text", max_length=128)
|
| 30 |
+
trainer = SFTTrainer(
|
| 31 |
+
model=peft_model,
|
| 32 |
+
args=training_args,
|
| 33 |
+
train_dataset=dataset,
|
| 34 |
+
processing_class=tokenizer,
|
| 35 |
+
)
|
| 36 |
+
trainer.train()
|
| 37 |
+
peft_model.save_pretrained("delora-llama-3-8b")
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
To utilize the fine-tuned DeLoRA modules, simply run the following command:
|
| 41 |
+
```python
|
| 42 |
+
import torch
|
| 43 |
+
from peft import PeftModel
|
| 44 |
+
from transformers import AutoModelForCausalLM
|
| 45 |
+
|
| 46 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 47 |
+
"meta-llama/Meta-Llama-3-8B", dtype=torch.bfloat16, device_map="auto"
|
| 48 |
+
)
|
| 49 |
+
peft_model = PeftModel.from_pretrained(model, "delora-llama-3-8b")
|
| 50 |
+
```
|
| 51 |
+
|
| 52 |
+
## Advanced Usage
|
| 53 |
+
In this script the default DeLoRA layers are the query and value layers of the Llama model. Adding adapters on more layers will increase memory usage. If you wish to choose a different set of layers for DeLoRA to be applied on, you can simply define it using:
|
| 54 |
+
```bash
|
| 55 |
+
python examples/delora_finetuning/delora_finetuning.py --base_model meta-llama/Meta-Llama-3-8B --target_modules "q_proj,k_proj,v_proj,o_proj"
|
| 56 |
+
```
|
| 57 |
+
|
| 58 |
+
Using different lambdas for different layers is also possible by setting `lambda_pattern`.
|
| 59 |
+
|
| 60 |
+
### Fine-tune
|
| 61 |
+
```bash
|
| 62 |
+
python delora_finetuning.py \
|
| 63 |
+
--base_model "PATH_TO_MODEL" \
|
| 64 |
+
--data_path "PATH_TO_DATASET" \
|
| 65 |
+
--output_dir "PATH_TO_OUTPUT_DIR" \
|
| 66 |
+
--batch_size 1 \
|
| 67 |
+
--num_epochs 3 \
|
| 68 |
+
--learning_rate 3e-3 \
|
| 69 |
+
--cutoff_len 512 \
|
| 70 |
+
--val_set_size 500 \
|
| 71 |
+
--eval_step 10 \
|
| 72 |
+
--save_step 100 \
|
| 73 |
+
--device "auto" \
|
| 74 |
+
--rank 32 \
|
| 75 |
+
--delora_lambda 15 \
|
| 76 |
+
--module_dropout 0.1 \
|
| 77 |
+
--target_modules "q_proj,v_proj" \
|
| 78 |
+
--hub_model_id "YOUR_HF_REPO" \
|
| 79 |
+
--push_to_hub
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
## Additional Notes
|
| 83 |
+
### Best practices
|
| 84 |
+
- use 10-100x larger learning rate than standard LoRA variants (typical values from 1e-3/1e-2/..)
|
| 85 |
+
- do not set a too small initial boundary parameter lambda (typical values are around 10/15/..)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
### DeLoRA vs DoRA
|
| 89 |
+
DeLoRA might feel quite similar to DoRA (given the similar target of decoupling angular from magnitude learning), however it presents key differences: (i) DoRA applies normalization and scaling operations on the fully finetuned weights ($W + \Delta W$), (ii) DoRA's normalization operation is performed on the column space of the weight matrices.
|
| 90 |
+
|
| 91 |
+
Conversely DeLoRA (i) introduces the normalization and scaling operations directly on the weight updates $\Delta W$, better preventing divergence from the pretrained model, and (ii) normalizes the inner low-dimensional space, which enforces a Frobenius-norm boundary to the weight updates.
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
## Citation
|
| 95 |
+
```
|
| 96 |
+
@inproceedings{bini2025decouplinganglesstrengthlowrank,
|
| 97 |
+
title={Decoupling Angles and Strength in Low-rank Adaptation},
|
| 98 |
+
author={Massimo Bini and Leander Girrbach and Zeynep Akata},
|
| 99 |
+
year={2025},
|
| 100 |
+
booktitle={International Conference on Learning Representations (ICLR)},
|
| 101 |
+
}
|
| 102 |
+
```
|
tasks/tasksmith-ecb1931929df/tests/source/examples/delora_finetuning/delora_finetuning.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This script is based on examples/randlora_finetuning/randlora_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 DeloraConfig, 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 |
+
rank: int,
|
| 30 |
+
delora_lambda: int,
|
| 31 |
+
module_dropout: float,
|
| 32 |
+
target_modules: str,
|
| 33 |
+
hub_model_id: str,
|
| 34 |
+
push_to_hub: bool,
|
| 35 |
+
):
|
| 36 |
+
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 37 |
+
hf_token = os.getenv("HF_TOKEN")
|
| 38 |
+
|
| 39 |
+
# Setup device
|
| 40 |
+
device = torch.device(device)
|
| 41 |
+
print(f"Using device: {device}")
|
| 42 |
+
|
| 43 |
+
# load tokenizer
|
| 44 |
+
tokenizer = AutoTokenizer.from_pretrained(base_model, token=hf_token)
|
| 45 |
+
|
| 46 |
+
# Compute type
|
| 47 |
+
device_type = device.type
|
| 48 |
+
device_module = getattr(torch, device_type, torch.cuda)
|
| 49 |
+
bf16_supported = device_module.is_available() and device_module.is_bf16_supported()
|
| 50 |
+
dtype = torch.bfloat16 if bf16_supported else torch.float32
|
| 51 |
+
|
| 52 |
+
# Load the base model
|
| 53 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 54 |
+
base_model,
|
| 55 |
+
dtype=dtype,
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
# DeLoRA config for the PEFT model
|
| 59 |
+
peft_config = DeloraConfig(
|
| 60 |
+
r=rank,
|
| 61 |
+
delora_lambda=delora_lambda,
|
| 62 |
+
target_modules=(target_modules.split(",") if target_modules else None),
|
| 63 |
+
module_dropout=module_dropout,
|
| 64 |
+
bias="none",
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
# get the peft model with DeLoRA config
|
| 68 |
+
model = get_peft_model(model, peft_config)
|
| 69 |
+
|
| 70 |
+
model.to(device) # MODEL TO ACCELERATOR
|
| 71 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 72 |
+
|
| 73 |
+
# Load the dataset
|
| 74 |
+
dataset = load_dataset(data_path)
|
| 75 |
+
|
| 76 |
+
def tokenize_function(examples):
|
| 77 |
+
inputs = tokenizer(examples["text"], padding="max_length", truncation=True, max_length=cutoff_len)
|
| 78 |
+
inputs["labels"] = inputs["input_ids"].copy() # setting labels for a language modeling task
|
| 79 |
+
return inputs
|
| 80 |
+
|
| 81 |
+
# Tokenize the dataset and prepare for training
|
| 82 |
+
tokenized_datasets = dataset.map(tokenize_function, batched=True, remove_columns=dataset["train"].column_names)
|
| 83 |
+
|
| 84 |
+
# Data collator to dynamically pad the batched examples
|
| 85 |
+
data_collator = DataCollatorForLanguageModeling(tokenizer, mlm=False)
|
| 86 |
+
|
| 87 |
+
# Compute the total amount of training step for warmup
|
| 88 |
+
max_steps = int((len(dataset) // batch_size) * num_epochs)
|
| 89 |
+
|
| 90 |
+
# Define training arguments
|
| 91 |
+
training_args = TrainingArguments(
|
| 92 |
+
output_dir=output_dir,
|
| 93 |
+
num_train_epochs=num_epochs,
|
| 94 |
+
per_device_train_batch_size=batch_size,
|
| 95 |
+
per_device_eval_batch_size=batch_size,
|
| 96 |
+
warmup_steps=int(max_steps * 0.1), # 10% of total trainig steps
|
| 97 |
+
weight_decay=0.0,
|
| 98 |
+
logging_steps=eval_step,
|
| 99 |
+
save_steps=save_step,
|
| 100 |
+
save_total_limit=2,
|
| 101 |
+
push_to_hub=push_to_hub,
|
| 102 |
+
hub_model_id=hub_model_id,
|
| 103 |
+
gradient_accumulation_steps=16,
|
| 104 |
+
learning_rate=learning_rate,
|
| 105 |
+
hub_token=hf_token,
|
| 106 |
+
label_names=["labels"],
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
# Clear accelerator cache to free memory
|
| 110 |
+
device_module.empty_cache()
|
| 111 |
+
|
| 112 |
+
# Initialize the Trainer
|
| 113 |
+
trainer = Trainer(
|
| 114 |
+
model=model,
|
| 115 |
+
args=training_args,
|
| 116 |
+
train_dataset=tokenized_datasets["train"],
|
| 117 |
+
eval_dataset=tokenized_datasets["test"],
|
| 118 |
+
data_collator=data_collator,
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
# Start model training
|
| 122 |
+
trainer.train()
|
| 123 |
+
|
| 124 |
+
# Save and push the trained model and tokenizer
|
| 125 |
+
if push_to_hub:
|
| 126 |
+
# Push the main model to the hub
|
| 127 |
+
trainer.push_to_hub(commit_message="Fine-tuned model")
|
| 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 DeLoRA")
|
| 138 |
+
parser.add_argument("--base_model", type=str, default="huggyllama/llama-7b", 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=3e-3, 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("--rank", type=int, default=32, help="DeLoRA basis rank")
|
| 154 |
+
parser.add_argument("--delora_lambda", type=int, default=640, help="DeLoRA alpha")
|
| 155 |
+
parser.add_argument("--module_dropout", type=float, default=0.05, help="DeLoRA dropout rate")
|
| 156 |
+
parser.add_argument(
|
| 157 |
+
"--target_modules", type=str, default=None, help="Comma-separated list of target modules for DeLoRA"
|
| 158 |
+
)
|
| 159 |
+
parser.add_argument(
|
| 160 |
+
"--hub_model_id",
|
| 161 |
+
type=str,
|
| 162 |
+
default="path/to/repo",
|
| 163 |
+
help="Repository name to push the model on the Hugging Face Hub",
|
| 164 |
+
)
|
| 165 |
+
parser.add_argument("--push_to_hub", action="store_true", help="Whether to push the model to Hugging Face Hub")
|
| 166 |
+
args = parser.parse_args()
|
| 167 |
+
|
| 168 |
+
if args.device == "auto":
|
| 169 |
+
args.device = torch.accelerator.current_accelerator().type if hasattr(torch, "accelerator") else "cuda"
|
| 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 |
+
rank=args.rank,
|
| 184 |
+
delora_lambda=args.delora_lambda,
|
| 185 |
+
module_dropout=args.module_dropout,
|
| 186 |
+
target_modules=args.target_modules,
|
| 187 |
+
hub_model_id=args.hub_model_id,
|
| 188 |
+
push_to_hub=args.push_to_hub,
|
| 189 |
+
)
|
tasks/tasksmith-ecb1931929df/tests/source/examples/dna_language_models/dna_lm.ipynb
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tasks/tasksmith-ecb1931929df/tests/source/examples/dora_finetuning/QDoRA_finetuning.ipynb
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tasks/tasksmith-ecb1931929df/tests/source/examples/dora_finetuning/README.md
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# DoRA: Weight-Decomposed Low-Rank Adaptation
|
| 2 |
+
|
| 3 |
+

|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
## Introduction
|
| 7 |
+
[DoRA](https://huggingface.co/papers/2402.09353) is a novel approach that leverages low rank adaptation through weight decomposition analysis to investigate the inherent differences between full fine-tuning and LoRA. DoRA initially decomposes the pretrained weight into its magnitude and directional components and finetunes both of them. Because the directional component is large in terms of parameter numbers, we further decompose it with LoRA for efficient finetuning. This results in enhancing both the learning capacity and training stability of LoRA while avoiding any additional inference overhead.
|
| 8 |
+
|
| 9 |
+
## Quick start
|
| 10 |
+
```python
|
| 11 |
+
import torch
|
| 12 |
+
from peft import LoraConfig, get_peft_model
|
| 13 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, Trainer
|
| 14 |
+
from datasets import load_dataset
|
| 15 |
+
|
| 16 |
+
model = AutoModelForCausalLM.from_pretrained("huggyllama/llama-7b", device_map="auto")
|
| 17 |
+
tokenizer = AutoTokenizer.from_pretrained("huggyllama/llama-7b")
|
| 18 |
+
dataset = load_dataset("timdettmers/openassistant-guanaco", split="train")
|
| 19 |
+
lora_config = LoraConfig(
|
| 20 |
+
use_dora=True
|
| 21 |
+
)
|
| 22 |
+
peft_model = get_peft_model(model, lora_config)
|
| 23 |
+
trainer = transformers.Trainer(
|
| 24 |
+
model=peft_model,
|
| 25 |
+
train_dataset=dataset,
|
| 26 |
+
dataset_text_field="text",
|
| 27 |
+
max_length=2048,
|
| 28 |
+
tokenizer=tokenizer,
|
| 29 |
+
)
|
| 30 |
+
trainer.train()
|
| 31 |
+
peft_model.save_pretrained("dora-llama-3-8b")
|
| 32 |
+
```
|
| 33 |
+
|
| 34 |
+
There is no additional change needed to your standard LoRA procedure, except for specifying `use_dora = True` option in your lora configuration.
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
Run the finetuning script simply by running:
|
| 38 |
+
```bash
|
| 39 |
+
python examples/dora_finetuning/dora_finetuning.py --base_model meta-llama/Meta-Llama-3-8B --data_path timdettmers/openassistant-guanaco
|
| 40 |
+
```
|
| 41 |
+
This 👆🏻 by default will load the model in peft set up with LoRA config. Now if you wanna quickly compare it with Dora, all you need to do is to input ` --use_dora` in the command line. So same above example would be 👇🏻;
|
| 42 |
+
|
| 43 |
+
```bash
|
| 44 |
+
python examples/dora_finetuning/dora_finetuning.py --base_model meta-llama/Meta-Llama-3-8B --data_path timdettmers/openassistant-guanaco --use_dora
|
| 45 |
+
```
|
| 46 |
+
|
| 47 |
+
DoRA also supports quantization. To use 4-bit quantization try:
|
| 48 |
+
|
| 49 |
+
```bash
|
| 50 |
+
python examples/dora_finetuning/dora_finetuning.py --base_model meta-llama/Meta-Llama-3-8B --quantize
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
Similarly, by default the LoRA layers are the attention and MLP layers of LLama model, if you get to choose a different set of layers for LoRA to be applied on, you can simply define it using:
|
| 54 |
+
```bash
|
| 55 |
+
python examples/dora_finetuning/dora_finetuning.py --lora_target_modules "q_proj,k_proj,v_proj,o_proj"
|
| 56 |
+
```
|
| 57 |
+
|
| 58 |
+
### Full example of the script
|
| 59 |
+
```bash
|
| 60 |
+
python dora_finetuning.py \
|
| 61 |
+
--base_model "PATH_TO_MODEL" \
|
| 62 |
+
--data_path "PATH_TO_DATASET" \
|
| 63 |
+
--output_dir "PATH_TO_OUTPUT_DIR" \
|
| 64 |
+
--batch_size 1 \
|
| 65 |
+
--num_epochs 3 \
|
| 66 |
+
--learning_rate 3e-4 \
|
| 67 |
+
--cutoff_len 512 \
|
| 68 |
+
--val_set_size 500 \
|
| 69 |
+
--use_dora \
|
| 70 |
+
--quantize \
|
| 71 |
+
--eval_step 10 \
|
| 72 |
+
--save_step 100 \
|
| 73 |
+
--lora_r 16 \
|
| 74 |
+
--lora_alpha 32 \
|
| 75 |
+
--lora_dropout 0.05 \
|
| 76 |
+
--lora_target_modules "q_proj,k_proj,v_proj,o_proj" \
|
| 77 |
+
--hub_model_id "YOUR_HF_REPO" \
|
| 78 |
+
--push_to_hub
|
| 79 |
+
```
|
| 80 |
+
## Use the model on 🤗
|
| 81 |
+
You can load and use the model as any other 🤗 models.
|
| 82 |
+
```python
|
| 83 |
+
from transformers import AutoModel
|
| 84 |
+
model = AutoModel.from_pretrained("ShirinYamani/huggyllama-llama-7b-finetuned")
|
| 85 |
+
```
|
| 86 |
+
|
| 87 |
+
## DoRA vs. LoRA
|
| 88 |
+
In general, DoRA finetuning on diffusion models is still experimental and is likely to require different hyperparameter values to perform best compared to LoRA.
|
| 89 |
+
|
| 90 |
+
Specifically, people have noticed 2 differences to take into account in your training:
|
| 91 |
+
|
| 92 |
+
1. LoRA seem to converge faster than DoRA (so a set of parameters that may lead to overfitting when training a LoRA may be working well for a DoRA)
|
| 93 |
+
|
| 94 |
+
2. DoRA quality superior to LoRA especially in lower ranks: The difference in quality of DoRA of rank 8 and LoRA of rank 8 appears to be more significant than when training ranks of 32 or 64 for example.
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
## Citation
|
| 98 |
+
```
|
| 99 |
+
@article{liu2024dora,
|
| 100 |
+
title={DoRA: Weight-Decomposed Low-Rank Adaptation},
|
| 101 |
+
author={Liu, Shih-Yang and Wang, Chien-Yi and Yin, Hongxu and Molchanov, Pavlo and Wang, Yu-Chiang Frank and Cheng, Kwang-Ting and Chen, Min-Hung},
|
| 102 |
+
journal={arXiv preprint arXiv:2402.09353},
|
| 103 |
+
year={2024}
|
| 104 |
+
}
|
| 105 |
+
```
|
tasks/tasksmith-ecb1931929df/tests/source/examples/dora_finetuning/dora_finetuning.py
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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fig,
|
| 9 |
+
DataCollatorForLanguageModeling,
|
| 10 |
+
Trainer,
|
| 11 |
+
TrainingArguments,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
|
| 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 |
+
use_dora: bool,
|
| 27 |
+
quantize: bool,
|
| 28 |
+
eval_step: int,
|
| 29 |
+
save_step: int,
|
| 30 |
+
device: str,
|
| 31 |
+
lora_r: int,
|
| 32 |
+
lora_alpha: int,
|
| 33 |
+
lora_dropout: float,
|
| 34 |
+
lora_target_modules: str,
|
| 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 |
+
# QDoRA (quantized dora): IF YOU WANNA QUANTIZE THE MODEL
|
| 52 |
+
if quantize:
|
| 53 |
+
if (torch.cuda.is_available() and torch.cuda.is_bf16_supported()) or torch.xpu.is_available():
|
| 54 |
+
bnb_4bit_compute_dtype = torch.bfloat16
|
| 55 |
+
else:
|
| 56 |
+
bnb_4bit_compute_dtype = torch.float16
|
| 57 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 58 |
+
base_model,
|
| 59 |
+
token=hf_token,
|
| 60 |
+
quantization_config=BitsAndBytesConfig(
|
| 61 |
+
load_in_4bit=True,
|
| 62 |
+
bnb_4bit_compute_dtype=bnb_4bit_compute_dtype,
|
| 63 |
+
bnb_4bit_use_double_quant=True,
|
| 64 |
+
bnb_4bit_quant_type="nf4",
|
| 65 |
+
),
|
| 66 |
+
)
|
| 67 |
+
# setup for quantized training
|
| 68 |
+
model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=True)
|
| 69 |
+
else:
|
| 70 |
+
model = AutoModelForCausalLM.from_pretrained(base_model, token=hf_token)
|
| 71 |
+
# LoRa config for the PEFT model
|
| 72 |
+
lora_config = LoraConfig(
|
| 73 |
+
use_dora=use_dora, # to use Dora OR compare to Lora just set the --use_dora
|
| 74 |
+
r=lora_r, # Rank of matrix
|
| 75 |
+
lora_alpha=lora_alpha,
|
| 76 |
+
target_modules=(
|
| 77 |
+
lora_target_modules.split(",")
|
| 78 |
+
if lora_target_modules
|
| 79 |
+
else ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
|
| 80 |
+
),
|
| 81 |
+
lora_dropout=lora_dropout,
|
| 82 |
+
bias="none",
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
# get the peft model with LoRa config
|
| 86 |
+
model = get_peft_model(model, lora_config)
|
| 87 |
+
|
| 88 |
+
model.to(device) # MODEL TO GPU/CUDA
|
| 89 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 90 |
+
|
| 91 |
+
# Load the dataset
|
| 92 |
+
dataset = load_dataset(data_path)
|
| 93 |
+
|
| 94 |
+
def tokenize_function(examples):
|
| 95 |
+
inputs = tokenizer(examples["text"], padding="max_length", truncation=True, max_length=cutoff_len)
|
| 96 |
+
inputs["labels"] = inputs["input_ids"].copy() # setting labels for a language modeling task
|
| 97 |
+
return inputs
|
| 98 |
+
|
| 99 |
+
# Tokenize the dataset and prepare for training
|
| 100 |
+
tokenized_datasets = dataset.map(tokenize_function, batched=True, remove_columns=dataset["train"].column_names)
|
| 101 |
+
|
| 102 |
+
# Data collator to dynamically pad the batched examples
|
| 103 |
+
data_collator = DataCollatorForLanguageModeling(tokenizer, mlm=False)
|
| 104 |
+
|
| 105 |
+
# Define training arguments
|
| 106 |
+
training_args = TrainingArguments(
|
| 107 |
+
output_dir=output_dir,
|
| 108 |
+
num_train_epochs=num_epochs,
|
| 109 |
+
per_device_train_batch_size=batch_size,
|
| 110 |
+
per_device_eval_batch_size=batch_size,
|
| 111 |
+
warmup_steps=100,
|
| 112 |
+
weight_decay=0.01,
|
| 113 |
+
logging_dir="./logs",
|
| 114 |
+
logging_steps=eval_step,
|
| 115 |
+
save_steps=save_step,
|
| 116 |
+
save_total_limit=2,
|
| 117 |
+
push_to_hub=push_to_hub,
|
| 118 |
+
hub_model_id=hub_model_id,
|
| 119 |
+
gradient_accumulation_steps=16,
|
| 120 |
+
fp16=True,
|
| 121 |
+
learning_rate=learning_rate,
|
| 122 |
+
hub_token=hf_token,
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
# Clear device cache to free memory
|
| 126 |
+
if torch.cuda.is_available():
|
| 127 |
+
torch.cuda.empty_cache()
|
| 128 |
+
elif torch.xpu.is_available():
|
| 129 |
+
torch.xpu.empty_cache()
|
| 130 |
+
|
| 131 |
+
# Initialize the Trainer
|
| 132 |
+
trainer = Trainer(
|
| 133 |
+
model=model,
|
| 134 |
+
args=training_args,
|
| 135 |
+
train_dataset=tokenized_datasets["train"],
|
| 136 |
+
eval_dataset=tokenized_datasets["test"],
|
| 137 |
+
data_collator=data_collator,
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
# Start model training
|
| 141 |
+
trainer.train()
|
| 142 |
+
|
| 143 |
+
# Save and push the trained model and tokenizer
|
| 144 |
+
if push_to_hub:
|
| 145 |
+
# Push the main model to the hub
|
| 146 |
+
trainer.push_to_hub(commit_message="Fine-tuned model")
|
| 147 |
+
|
| 148 |
+
# Save the model and tokenizer locally
|
| 149 |
+
model.save_pretrained(output_dir)
|
| 150 |
+
tokenizer.save_pretrained(output_dir)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
if __name__ == "__main__":
|
| 154 |
+
import argparse
|
| 155 |
+
|
| 156 |
+
parser = argparse.ArgumentParser(description="Fine-tune LLaMA with DoRA and PEFT")
|
| 157 |
+
parser.add_argument("--base_model", type=str, default="huggyllama/llama-7b", help="Base model path or name")
|
| 158 |
+
parser.add_argument(
|
| 159 |
+
"--data_path", type=str, default="timdettmers/openassistant-guanaco", help="Dataset path or name"
|
| 160 |
+
)
|
| 161 |
+
parser.add_argument(
|
| 162 |
+
"--output_dir", type=str, default="path/to/output", help="Output directory for the fine-tuned model"
|
| 163 |
+
)
|
| 164 |
+
parser.add_argument("--batch_size", type=int, default=1, help="Batch size")
|
| 165 |
+
parser.add_argument("--num_epochs", type=int, default=1, help="Number of training epochs")
|
| 166 |
+
parser.add_argument("--learning_rate", type=float, default=3e-4, help="Learning rate")
|
| 167 |
+
parser.add_argument("--cutoff_len", type=int, default=512, help="Cutoff length for tokenization")
|
| 168 |
+
parser.add_argument("--val_set_size", type=int, default=500, help="Validation set size")
|
| 169 |
+
parser.add_argument("--use_dora", action="store_true", help="Apply Dora")
|
| 170 |
+
parser.add_argument("--quantize", action="store_true", help="Use quantization")
|
| 171 |
+
parser.add_argument("--eval_step", type=int, default=10, help="Evaluation step interval")
|
| 172 |
+
parser.add_argument("--save_step", type=int, default=100, help="Save step interval")
|
| 173 |
+
parser.add_argument("--device", type=str, default="auto", help="Device to use for training")
|
| 174 |
+
parser.add_argument("--lora_r", type=int, default=8, help="LoRA rank")
|
| 175 |
+
parser.add_argument("--lora_alpha", type=int, default=16, help="LoRA alpha")
|
| 176 |
+
parser.add_argument("--lora_dropout", type=float, default=0.05, help="LoRA dropout rate")
|
| 177 |
+
parser.add_argument(
|
| 178 |
+
"--lora_target_modules", type=str, default=None, help="Comma-separated list of target modules for LoRA"
|
| 179 |
+
)
|
| 180 |
+
parser.add_argument(
|
| 181 |
+
"--hub_model_id",
|
| 182 |
+
type=str,
|
| 183 |
+
default="path/to/repo",
|
| 184 |
+
help="Repository name to push the model on the Hugging Face Hub",
|
| 185 |
+
)
|
| 186 |
+
parser.add_argument("--push_to_hub", action="store_true", help="Whether to push the model to Hugging Face Hub")
|
| 187 |
+
args = parser.parse_args()
|
| 188 |
+
train_model(
|
| 189 |
+
base_model=args.base_model,
|
| 190 |
+
data_path=args.data_path,
|
| 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 |
+
cutoff_len=args.cutoff_len,
|
| 196 |
+
val_set_size=args.val_set_size,
|
| 197 |
+
use_dora=args.use_dora,
|
| 198 |
+
quantize=args.quantize,
|
| 199 |
+
eval_step=args.eval_step,
|
| 200 |
+
save_step=args.save_step,
|
| 201 |
+
device=args.device,
|
| 202 |
+
lora_r=args.lora_r,
|
| 203 |
+
lora_alpha=args.lora_alpha,
|
| 204 |
+
lora_dropout=args.lora_dropout,
|
| 205 |
+
lora_target_modules=args.lora_target_modules,
|
| 206 |
+
hub_model_id=args.hub_model_id,
|
| 207 |
+
push_to_hub=args.push_to_hub,
|
| 208 |
+
)
|
tasks/tasksmith-ecb1931929df/tests/source/examples/ephemeral_gpu_offloading/load_with_dora.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
Example script demonstrating the time difference loading a model with a DoRA using ephemeral GPU offloading vs doing it purely on the CPU.
|
| 17 |
+
|
| 18 |
+
Example outputs:
|
| 19 |
+
$ python load_with_dora.py
|
| 20 |
+
--- Loading model ---
|
| 21 |
+
Loading checkpoint shards: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████| 4/4 [00:04<00:00, 1.03s/it]
|
| 22 |
+
--- Loading PeftModel ---
|
| 23 |
+
--- Done ---
|
| 24 |
+
Model loading time: 4.83s
|
| 25 |
+
PeftModel loading time: 28.14s
|
| 26 |
+
Use ephemeral GPU offloading: False
|
| 27 |
+
|
| 28 |
+
(Note: if this was the first time you ran the script, or if your cache was cleared, the times shown above are invalid, due to the time taken to download the model and DoRA files. Just re-run the script in this case.)
|
| 29 |
+
|
| 30 |
+
$ python load_with_dora.py --ephemeral_gpu_offload
|
| 31 |
+
--- Loading model ---
|
| 32 |
+
Loading checkpoint shards: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████| 4/4 [00:03<00:00, 1.11it/s]
|
| 33 |
+
--- Loading PeftModel ---
|
| 34 |
+
--- Done ---
|
| 35 |
+
Model loading time: 4.28s
|
| 36 |
+
PeftModel loading time: 16.59s
|
| 37 |
+
Use ephemeral GPU offloading: True
|
| 38 |
+
|
| 39 |
+
(Note: if this was the first time you ran the script, or if your cache was cleared, the times shown above are invalid, due to the time taken to download the model and DoRA files. Just re-run the script in this case.)
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
import argparse
|
| 43 |
+
import time
|
| 44 |
+
|
| 45 |
+
from huggingface_hub import snapshot_download
|
| 46 |
+
from transformers import AutoModelForCausalLM
|
| 47 |
+
|
| 48 |
+
from peft import PeftModel
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def main():
|
| 52 |
+
parser = argparse.ArgumentParser(description="Load a model with DoRA using ephemeral GPU offloading")
|
| 53 |
+
parser.add_argument("--model", type=str, default="NousResearch/Hermes-2-Pro-Mistral-7B", help="Model to load")
|
| 54 |
+
parser.add_argument(
|
| 55 |
+
"--dora",
|
| 56 |
+
type=str,
|
| 57 |
+
default="peft-internal-testing/DoRA-Hermes-2-Pro-Mistral-7B",
|
| 58 |
+
help="DoRA to use",
|
| 59 |
+
)
|
| 60 |
+
parser.add_argument("--ephemeral_gpu_offload", action="store_true", help="Use ephemeral GPU offloading")
|
| 61 |
+
parser.add_argument(
|
| 62 |
+
"--merge_model_path", type=str, help="Merge the model with the DoRA model and save to the given path"
|
| 63 |
+
)
|
| 64 |
+
args = parser.parse_args()
|
| 65 |
+
|
| 66 |
+
peft_model_kwargs = {
|
| 67 |
+
"ephemeral_gpu_offload": args.ephemeral_gpu_offload,
|
| 68 |
+
"max_memory": {"cpu": "256GiB"},
|
| 69 |
+
"device_map": {"": "cpu"},
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
# Predownload
|
| 73 |
+
try:
|
| 74 |
+
snapshot_download(repo_id=args.model)
|
| 75 |
+
except Exception as e:
|
| 76 |
+
print(f"Failed to download model: {e}")
|
| 77 |
+
# We continue anyway as this might be e.g. a local directory or something
|
| 78 |
+
try:
|
| 79 |
+
snapshot_download(repo_id=args.dora)
|
| 80 |
+
except Exception as e:
|
| 81 |
+
print(f"Failed to download DoRA: {e}")
|
| 82 |
+
# We continue anyway as this might be e.g. a local directory or something
|
| 83 |
+
|
| 84 |
+
start = time.perf_counter()
|
| 85 |
+
print("--- Loading model ---")
|
| 86 |
+
model = AutoModelForCausalLM.from_pretrained(args.model)
|
| 87 |
+
model_time = time.perf_counter() - start
|
| 88 |
+
print("--- Loading PeftModel ---")
|
| 89 |
+
peft_model = PeftModel.from_pretrained(model, args.dora, **peft_model_kwargs)
|
| 90 |
+
print("--- Done ---")
|
| 91 |
+
peft_model_time = time.perf_counter() - start
|
| 92 |
+
|
| 93 |
+
print(f"Model loading time: {model_time:.2f}s")
|
| 94 |
+
print(f"PeftModel loading time: {peft_model_time:.2f}s")
|
| 95 |
+
print(f"Use ephemeral GPU offloading: {args.ephemeral_gpu_offload}")
|
| 96 |
+
|
| 97 |
+
if args.merge_model_path is not None:
|
| 98 |
+
merged_model = peft_model.merge_and_unload(progressbar=True)
|
| 99 |
+
merged_model.save_pretrained(args.merge_model_path)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
if __name__ == "__main__":
|
| 103 |
+
main()
|
tasks/tasksmith-ecb1931929df/tests/source/examples/eva_finetuning/README.md
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
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| 3 |
+
Explained Variance Adaptation (EVA) is a novel initialization method for LoRA style adapters which initializes adapter weights in a data driven manner and adaptively allocates ranks according to the variance they explain. EVA improves average performance on a multitude of tasks across various domains, such as Language generation and understanding, Image classification, and Decision Making.
|
| 4 |
+
|
| 5 |
+
The abstract from the paper is:
|
| 6 |
+
|
| 7 |
+
*Foundation models (FMs) are pre-trained on large-scale datasets and then fine-tuned on a downstream task for a specific application. The most successful and most commonly used fine-tuning method is to update the pre-trained weights via a low-rank adaptation (LoRA). LoRA introduces new weight matrices that are usually initialized at random with a uniform rank distribution across model weights. Recent works focus on weight-driven initialization or learning of adaptive ranks during training. Both approaches have only been investigated in isolation, resulting in slow convergence or a uniform rank distribution, in turn leading to sub-optimal performance. We propose to enhance LoRA by initializing the new weights in a data-driven manner by computing singular value decomposition on minibatches of activation vectors. Then, we initialize the LoRA matrices with the obtained right-singular vectors and re-distribute ranks among all weight matrices to explain the maximal amount of variance and continue the standard LoRA fine-tuning procedure. This results in our new method **E**xplained **V**ariance **A**daptation (EVA). We apply EVA to a variety of fine-tuning tasks ranging from language generation and understanding to image classification and reinforcement learning. EVA exhibits faster convergence than competitors and attains the highest average score across a multitude of tasks per domain.*
|
| 8 |
+
|
| 9 |
+
## Quick Start
|
| 10 |
+
Below is an example of how to use EVA with a causal language model. For a more detailed example see [eva_finetuning.py](https://github.com/huggingface/peft/blob/main/examples/eva_finetuning/eva_finetuning.py).
|
| 11 |
+
```python
|
| 12 |
+
import torch
|
| 13 |
+
from datasets import load_dataset
|
| 14 |
+
from torch.utils.data import DataLoader
|
| 15 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 16 |
+
|
| 17 |
+
from peft import EvaConfig, LoraConfig, get_peft_model, initialize_lora_eva_weights
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
# config
|
| 21 |
+
model_name = "meta-llama/Llama-3.1-8B"
|
| 22 |
+
max_seq_len = 512
|
| 23 |
+
rank = 16
|
| 24 |
+
alpha = 1
|
| 25 |
+
rho = 2.0
|
| 26 |
+
target_modules = ["q_proj", "k_proj", "v_proj", "o_proj"]
|
| 27 |
+
svd_batch_size = 4 # can be different from the batch size used in finetuning
|
| 28 |
+
|
| 29 |
+
# load model and tokenizer
|
| 30 |
+
model = AutoModelForCausalLM.from_pretrained(model_name)
|
| 31 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 32 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 33 |
+
|
| 34 |
+
# load dataset
|
| 35 |
+
dataset = load_dataset("Rowan/hellaswag")
|
| 36 |
+
dataset = dataset.map(
|
| 37 |
+
lambda x: tokenizer(x["ctx"], padding="max_length", truncation=True, max_length=max_seq_len),
|
| 38 |
+
batched=True,
|
| 39 |
+
remove_columns=dataset["train"].column_names,
|
| 40 |
+
)
|
| 41 |
+
dataset.set_format(type="torch")
|
| 42 |
+
|
| 43 |
+
# create dataloader for SVD
|
| 44 |
+
# typically this is the same as the dataloader used for finetuning
|
| 45 |
+
dataloader = DataLoader(
|
| 46 |
+
dataset["train"],
|
| 47 |
+
batch_size=svd_batch_size,
|
| 48 |
+
collate_fn=lambda examples: {k: torch.stack([v[k] for v in examples], dim=0) for k in examples[0].keys()},
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
# setup peft config
|
| 52 |
+
eva_config = EvaConfig(
|
| 53 |
+
rho=rho
|
| 54 |
+
)
|
| 55 |
+
peft_config = LoraConfig(
|
| 56 |
+
r=rank,
|
| 57 |
+
lora_alpha=alpha,
|
| 58 |
+
target_modules=target_modules,
|
| 59 |
+
init_lora_weights="eva",
|
| 60 |
+
eva_config=eva_config
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
# move model to accelerator
|
| 64 |
+
device = torch.accelerator.current_accelerator().type if hasattr(torch, "accelerator") else "cuda"
|
| 65 |
+
model = model.to(device)
|
| 66 |
+
|
| 67 |
+
# to optimize memory usage during EVA initialization, set low_cpu_mem_usage=True
|
| 68 |
+
peft_model = get_peft_model(model, peft_config, low_cpu_mem_usage=True)
|
| 69 |
+
|
| 70 |
+
initialize_lora_eva_weights(peft_model, dataloader)
|
| 71 |
+
```
|
| 72 |
+
`initialize_lora_eva_weights` will compute the SVD and load the components into the model. After this continue with standard LoRA finetuning.
|
| 73 |
+
|
| 74 |
+
## Using EVA with Bitsandbytes
|
| 75 |
+
EVA is fully compatible with bitsandbytes. Simply initialize the pretrained model with a BitsAndBytesConfig and then use the peft model with EVA.
|
| 76 |
+
```python
|
| 77 |
+
from transformers import BitsAndBytesConfig
|
| 78 |
+
from peft import prepare_model_for_kbit_training
|
| 79 |
+
|
| 80 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 81 |
+
"meta-llama/Llama-3.1-8B",
|
| 82 |
+
quantization_config=BitsAndBytesConfig(load_in_4bit=True)
|
| 83 |
+
)
|
| 84 |
+
model = prepare_model_for_kbit_training(model)
|
| 85 |
+
peft_model = get_peft_model(model, peft_config)
|
| 86 |
+
initialize_lora_eva_weights(peft_model, dataloader)
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
## Getting the EVA state_dict without loading the adapter weights
|
| 90 |
+
In some cases you might just want to get the state_dict after EVA initialization without loading the adapter weights. This can be useful for example if:
|
| 91 |
+
- you want to precompute and store the state_dict for different downstream tasks.
|
| 92 |
+
- you need to quantize the model for finetuning but want to perform EVA initialization with model weights in full/half precision.
|
| 93 |
+
- you do not intend to use a peft model for LoRA finetuning.
|
| 94 |
+
- you would like to leverage multiple accelerators for EVA initialization. (At the moment this is not directly supported by `initialize_lora_eva_weights`)
|
| 95 |
+
|
| 96 |
+
You can do this by calling `get_eva_state_dict` directly (you only need to pass `peft_config` if `model` is not a PeftModel):
|
| 97 |
+
```python
|
| 98 |
+
from peft import get_eva_state_dict
|
| 99 |
+
|
| 100 |
+
eva_state_dict = get_eva_state_dict(model, dataloader, peft_config)
|
| 101 |
+
```
|
| 102 |
+
Later you can load the state_dict into a `PeftModel` by using the `eva_state_dict` argument in `initialize_lora_eva_weights`:
|
| 103 |
+
```python
|
| 104 |
+
initialize_lora_eva_weights(peft_model, eva_state_dict=eva_state_dict)
|
| 105 |
+
```
|
| 106 |
+
|
| 107 |
+
## Leveraging multiple accelerators
|
| 108 |
+
|
| 109 |
+
EVA initialization can be parallelized across multiple accelerators. In this case inputs from multiple accelerators are gathered before computing the SVD for the batch. This requires that the model is wrapped in a `torch.nn.DataParallel` or `torch.nn.DistributedDataParallel` class. An example of how to use this can be found in [eva_finetuning_multi_accelerator.py](https://github.com/huggingface/peft/blob/main/examples/eva_finetuning/eva_finetuning_multi_accelerator.py).
|
| 110 |
+
|
| 111 |
+
## Customizing EVA
|
| 112 |
+
|
| 113 |
+
By default, EVA is designed to work with standard transformer language models. However we integrated three different parameters which can be used to customize EVA for other types of models.
|
| 114 |
+
1. `forward_fn`: Defines how the forward pass during EVA initialization should be computed.
|
| 115 |
+
2. `prepare_model_inputs_fn`: Can be used if it is necessary to use information contained in the original model_input to prepare the input for SVD in individual layers.
|
| 116 |
+
3. `prepare_layer_inputs_fn`: Defines how layer inputs should be prepared for SVD.
|
| 117 |
+
|
| 118 |
+
All three parameters can be passed to `initialize_lora_eva_weights` and `get_eva_state_dict`.
|
| 119 |
+
|
| 120 |
+
### forward_fn
|
| 121 |
+
|
| 122 |
+
`forward_fn` defines how the forward pass during EVA initialization should be computed. `forward_fn` receives two arguments: `model` and `inputs`. By default this is set to `forward_fn_dict` which simply returns `model(**inputs)`.
|
| 123 |
+
|
| 124 |
+
### prepare_model_inputs_fn
|
| 125 |
+
|
| 126 |
+
`prepare_model_inputs_fn` can be used if it is necessary to use information contained in the original model_input to prepare the input for SVD in individual layers. `prepare_model_inputs_fn` receives two arguments: `model_input` and `peft_config`. This component is separate from `prepare_layer_inputs_fn` as the output only needs to be computed once per batch. By default this parameter is set to `prepare_model_inputs_fn_language_modeling` which is used get a subset of indices based on attention and label mask to avoid including padding tokens in the SVD computation. If you would like to not use this component set `prepare_model_inputs_fn` to None. The default logic is:
|
| 127 |
+
```python
|
| 128 |
+
def prepare_model_inputs_fn_language_modeling(model_input, peft_config: LoraConfig):
|
| 129 |
+
mask = model_input.get("attention_mask", torch.ones_like(model_input["input_ids"])).bool()
|
| 130 |
+
if peft_config.eva_config.use_label_mask and hasattr(model_input, "labels"):
|
| 131 |
+
mask = torch.logical_and(mask, model_input["labels"] != peft_config.eva_config.label_mask_value)
|
| 132 |
+
return mask.nonzero()
|
| 133 |
+
```
|
| 134 |
+
|
| 135 |
+
### prepare_layer_inputs_fn
|
| 136 |
+
|
| 137 |
+
`prepare_layer_inputs_fn` can be used to preprocess the layer inputs before passing them to the SVD algorithm. `prepare_layer_inputs_fn` receives three arguments: `layer_input`, `model_input` and `layer_name`. It can either be a callable or a dictionary where the keys are the layer names and the values are callables. If it is a dictionary, functions are assigned to adapter layers based on the layer names. By default a language modeling setting is assumed where model_inputs are the outputs of `prepare_model_inputs_fn_language_modeling` which is a mask of indices. If this parameter is set to None, only two modifications are made to the layer inputs
|
| 138 |
+
- take the first element incase of a tuple or list.
|
| 139 |
+
- if the input has more than 2 dimensions, we flatten all but the last dimension.
|
| 140 |
+
|
| 141 |
+
Must always return a tensor. The default logic is:
|
| 142 |
+
```python
|
| 143 |
+
def prepare_layer_inputs_fn_default(layer_input, model_input, layer_name) -> torch.Tensor:
|
| 144 |
+
if isinstance(layer_input, (tuple, list)):
|
| 145 |
+
layer_input = layer_input[0]
|
| 146 |
+
return layer_input[model_input.T.unbind()]
|
| 147 |
+
```
|
| 148 |
+
|
| 149 |
+
## Citation
|
| 150 |
+
In case you find our work useful, please consider citing it.
|
| 151 |
+
|
| 152 |
+
```
|
| 153 |
+
@article{paischer2024eva,
|
| 154 |
+
title={One Initialization to Rule them All: Fine-tuning via Explained Variance Adaptation},
|
| 155 |
+
author={Fabian Paischer, Lukas Hauzenberger, Thomas Schmied, Benedikt Alkin, Marc Peter Deisenroth, Sepp Hochreiter},
|
| 156 |
+
journal={arXiv preprint arXiv:2410.07170},
|
| 157 |
+
year={2024}
|
| 158 |
+
}
|
| 159 |
+
```
|
tasks/tasksmith-ecb1931929df/tests/source/examples/eva_finetuning/eva_finetuning.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
import torch
|
| 16 |
+
from datasets import load_dataset
|
| 17 |
+
from torch.utils.data import DataLoader
|
| 18 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, Trainer, TrainingArguments
|
| 19 |
+
from utils import DataCollator, TokenizerMetaMath
|
| 20 |
+
|
| 21 |
+
from peft import EvaConfig, LoraConfig, get_peft_model, initialize_lora_eva_weights
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
DEVICE = torch.accelerator.current_accelerator().type if hasattr(torch, "accelerator") else "cuda"
|
| 25 |
+
|
| 26 |
+
# config
|
| 27 |
+
model_name = "meta-llama/Llama-3.1-8B"
|
| 28 |
+
max_seq_len = 512
|
| 29 |
+
rank = 16
|
| 30 |
+
alpha = 1
|
| 31 |
+
rho = 2.0
|
| 32 |
+
target_modules = ["q_proj", "k_proj", "v_proj", "o_proj"]
|
| 33 |
+
svd_batch_size = 4 # can be different from the batch size used in finetuning
|
| 34 |
+
batch_size = 4
|
| 35 |
+
learning_rate = 5e-4
|
| 36 |
+
gradient_accumulation_steps = 8
|
| 37 |
+
num_epochs = 1
|
| 38 |
+
output_dir = "outputs"
|
| 39 |
+
bf16 = True
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# load model and tokenizer
|
| 43 |
+
model = AutoModelForCausalLM.from_pretrained(model_name)
|
| 44 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 45 |
+
|
| 46 |
+
# load dataset
|
| 47 |
+
dataset = load_dataset("meta-math/MetaMathQA")
|
| 48 |
+
dataset = dataset.map(
|
| 49 |
+
TokenizerMetaMath(model_name),
|
| 50 |
+
batched=True,
|
| 51 |
+
remove_columns=dataset["train"].column_names,
|
| 52 |
+
)
|
| 53 |
+
dataset.set_format(type="torch")
|
| 54 |
+
|
| 55 |
+
# data collator
|
| 56 |
+
data_collator = DataCollator(tokenizer.eos_token_id, max_length=max_seq_len)
|
| 57 |
+
|
| 58 |
+
# dataloader
|
| 59 |
+
dataloader = DataLoader(
|
| 60 |
+
dataset["train"],
|
| 61 |
+
batch_size=svd_batch_size,
|
| 62 |
+
collate_fn=data_collator,
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
# setup peft config
|
| 66 |
+
eva_config = EvaConfig(rho=rho)
|
| 67 |
+
peft_config = LoraConfig(
|
| 68 |
+
r=rank, lora_alpha=alpha, target_modules=target_modules, init_lora_weights="eva", eva_config=eva_config
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
# move model to accelerator
|
| 72 |
+
model = model.to(DEVICE)
|
| 73 |
+
|
| 74 |
+
# to optimize memory usage during eva initialization, set low_cpu_mem_usage=True
|
| 75 |
+
peft_model = get_peft_model(model, peft_config, low_cpu_mem_usage=True)
|
| 76 |
+
initialize_lora_eva_weights(peft_model, dataloader)
|
| 77 |
+
|
| 78 |
+
# setup training arguments
|
| 79 |
+
training_args = TrainingArguments(
|
| 80 |
+
per_device_train_batch_size=batch_size,
|
| 81 |
+
learning_rate=learning_rate,
|
| 82 |
+
gradient_accumulation_steps=gradient_accumulation_steps,
|
| 83 |
+
num_train_epochs=num_epochs,
|
| 84 |
+
output_dir=output_dir,
|
| 85 |
+
remove_unused_columns=False,
|
| 86 |
+
bf16=bf16,
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
# continue with standard finetuning
|
| 90 |
+
trainer = Trainer(
|
| 91 |
+
model=peft_model,
|
| 92 |
+
args=training_args,
|
| 93 |
+
train_dataset=dataset["train"],
|
| 94 |
+
data_collator=data_collator,
|
| 95 |
+
)
|
| 96 |
+
trainer.train()
|
tasks/tasksmith-ecb1931929df/tests/source/examples/eva_finetuning/eva_finetuning_multi_accelerator.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
import os
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
import torch.distributed as dist
|
| 19 |
+
from datasets import load_dataset
|
| 20 |
+
from torch.nn.parallel import DistributedDataParallel as DDP
|
| 21 |
+
from torch.utils.data import DataLoader
|
| 22 |
+
from torch.utils.data.distributed import DistributedSampler
|
| 23 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, Trainer, TrainingArguments
|
| 24 |
+
from utils import DataCollator, TokenizerMetaMath
|
| 25 |
+
|
| 26 |
+
from peft import EvaConfig, LoraConfig, get_eva_state_dict, get_peft_model, initialize_lora_eva_weights
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# run this script e.g. with: torchrun --nproc_per_node=4 eva_finetuning_multi_gpu.py
|
| 30 |
+
|
| 31 |
+
# config
|
| 32 |
+
model_name = "meta-llama/Llama-2-7b-hf"
|
| 33 |
+
max_seq_len = 512
|
| 34 |
+
rank = 16
|
| 35 |
+
alpha = 1
|
| 36 |
+
rho = 2.0
|
| 37 |
+
target_modules = ["q_proj", "k_proj", "v_proj", "o_proj"]
|
| 38 |
+
svd_batch_size = 4 # can be different from the batch size used in finetuning
|
| 39 |
+
batch_size = 4
|
| 40 |
+
learning_rate = 5e-4
|
| 41 |
+
gradient_accumulation_steps = 8
|
| 42 |
+
num_epochs = 1
|
| 43 |
+
output_dir = "outputs"
|
| 44 |
+
bf16 = True
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
# Initialize distributed environment
|
| 48 |
+
if torch.cuda.is_available():
|
| 49 |
+
local_rank = int(os.environ.get("LOCAL_RANK", -1))
|
| 50 |
+
torch.cuda.set_device(local_rank)
|
| 51 |
+
dist.init_process_group("nccl")
|
| 52 |
+
world_size = dist.get_world_size()
|
| 53 |
+
elif torch.xpu.is_available():
|
| 54 |
+
local_rank = int(os.environ.get("LOCAL_RANK", -1))
|
| 55 |
+
torch.xpu.set_device(local_rank)
|
| 56 |
+
dist.init_process_group("xccl")
|
| 57 |
+
world_size = dist.get_world_size()
|
| 58 |
+
else:
|
| 59 |
+
local_rank = -1
|
| 60 |
+
world_size = 1
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
# load model and tokenizer
|
| 64 |
+
model = AutoModelForCausalLM.from_pretrained(model_name)
|
| 65 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 66 |
+
|
| 67 |
+
# load dataset
|
| 68 |
+
dataset = load_dataset("meta-math/MetaMathQA")
|
| 69 |
+
dataset = dataset.map(
|
| 70 |
+
TokenizerMetaMath(model_name),
|
| 71 |
+
batched=True,
|
| 72 |
+
remove_columns=dataset["train"].column_names,
|
| 73 |
+
)
|
| 74 |
+
dataset.set_format(type="torch")
|
| 75 |
+
|
| 76 |
+
# data collator
|
| 77 |
+
data_collator = DataCollator(tokenizer.eos_token_id, max_length=max_seq_len)
|
| 78 |
+
|
| 79 |
+
# Create sampler for distributed training
|
| 80 |
+
sampler = DistributedSampler(dataset["train"], num_replicas=world_size, rank=local_rank)
|
| 81 |
+
|
| 82 |
+
# dataloader
|
| 83 |
+
dataloader = DataLoader(
|
| 84 |
+
dataset["train"],
|
| 85 |
+
batch_size=svd_batch_size,
|
| 86 |
+
collate_fn=data_collator,
|
| 87 |
+
sampler=sampler,
|
| 88 |
+
shuffle=False,
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
sampler.set_epoch(0)
|
| 92 |
+
|
| 93 |
+
# Wrap model in DDP
|
| 94 |
+
model = model.to(local_rank)
|
| 95 |
+
model = DDP(model, device_ids=[local_rank], output_device=local_rank)
|
| 96 |
+
|
| 97 |
+
# setup peft config
|
| 98 |
+
eva_config = EvaConfig(rho=rho)
|
| 99 |
+
peft_config = LoraConfig(
|
| 100 |
+
r=rank, lora_alpha=alpha, target_modules=target_modules, init_lora_weights="eva", eva_config=eva_config
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
# EVA initialization
|
| 104 |
+
eva_state_dict = get_eva_state_dict(model, dataloader, peft_config)
|
| 105 |
+
eva_state_dict = {".".join(["base_model.model"] + k.split(".")[1:]): v for k, v in eva_state_dict.items()}
|
| 106 |
+
|
| 107 |
+
# cleanup ddp
|
| 108 |
+
model = model.module
|
| 109 |
+
|
| 110 |
+
# initialize peft model
|
| 111 |
+
peft_model = get_peft_model(model, peft_config, low_cpu_mem_usage=True)
|
| 112 |
+
initialize_lora_eva_weights(peft_model, eva_state_dict=eva_state_dict)
|
| 113 |
+
|
| 114 |
+
# setup training arguments
|
| 115 |
+
training_args = TrainingArguments(
|
| 116 |
+
per_device_train_batch_size=batch_size,
|
| 117 |
+
learning_rate=learning_rate,
|
| 118 |
+
gradient_accumulation_steps=gradient_accumulation_steps,
|
| 119 |
+
num_train_epochs=num_epochs,
|
| 120 |
+
output_dir=output_dir,
|
| 121 |
+
remove_unused_columns=False,
|
| 122 |
+
bf16=bf16,
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
# continue with standard finetuning
|
| 126 |
+
trainer = Trainer(
|
| 127 |
+
model=peft_model,
|
| 128 |
+
args=training_args,
|
| 129 |
+
train_dataset=dataset["train"],
|
| 130 |
+
data_collator=data_collator,
|
| 131 |
+
)
|
| 132 |
+
trainer.train()
|
tasks/tasksmith-ecb1931929df/tests/source/examples/eva_finetuning/utils.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
import torch
|
| 16 |
+
from transformers import AutoTokenizer
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class TokenizerMetaMath:
|
| 20 |
+
PROMPT_NO_INPUT = (
|
| 21 |
+
"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n"
|
| 22 |
+
"### Instruction:\n{query}\n\n### Response: "
|
| 23 |
+
)
|
| 24 |
+
PROMPT = (
|
| 25 |
+
"Below is an instruction that describes a task, paired with an input that provides further context. "
|
| 26 |
+
"Write a response that appropriately completes the request.\n\n"
|
| 27 |
+
"### Instruction:\n{query}\n\n### Input:\n{input}\n\n### Response: "
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
def format_prompt(self, query):
|
| 31 |
+
query = query.split("\n", 1)
|
| 32 |
+
if len(query) == 1 or query[1].strip("\n") == "":
|
| 33 |
+
return self.PROMPT_NO_INPUT.format(query=query[0])
|
| 34 |
+
else:
|
| 35 |
+
return self.PROMPT.format(query=query[0], input=query[1])
|
| 36 |
+
|
| 37 |
+
def __init__(self, tokenizer_path):
|
| 38 |
+
self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_path)
|
| 39 |
+
|
| 40 |
+
def __call__(self, examples):
|
| 41 |
+
prompts = [self.format_prompt(text) for text in examples["query"]]
|
| 42 |
+
completions = examples["response"]
|
| 43 |
+
return self._tokenize_fn(prompts, completions)
|
| 44 |
+
|
| 45 |
+
def _tokenize_fn(self, prompts, completions):
|
| 46 |
+
prompt_tokens = self.tokenizer(prompts, add_special_tokens=False)["input_ids"]
|
| 47 |
+
input_tokens = self.tokenizer([x + y for x, y in zip(prompts, completions)], add_special_tokens=False)[
|
| 48 |
+
"input_ids"
|
| 49 |
+
]
|
| 50 |
+
input_tokens = [[self.tokenizer.bos_token_id] + x + [self.tokenizer.eos_token_id] for x in input_tokens]
|
| 51 |
+
prompt_length = [len(x) + 1 for x in prompt_tokens] # +1 for the bos token
|
| 52 |
+
input_length = [len(x) for x in input_tokens]
|
| 53 |
+
return {"input_ids": input_tokens, "prompt_length": prompt_length, "input_length": input_length}
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class DataCollator:
|
| 57 |
+
def __init__(self, eos_token_id, max_length=None):
|
| 58 |
+
self.eos_token_id = eos_token_id
|
| 59 |
+
self.max_length = max_length
|
| 60 |
+
|
| 61 |
+
def __call__(self, batch):
|
| 62 |
+
batch = {k: [item[k] for item in batch] for k in batch[0]}
|
| 63 |
+
input_lengths = torch.stack(batch["input_length"])
|
| 64 |
+
prompt_lengths = torch.stack(batch["prompt_length"])
|
| 65 |
+
input_ids = torch.nn.utils.rnn.pad_sequence(
|
| 66 |
+
batch["input_ids"], batch_first=True, padding_value=self.eos_token_id
|
| 67 |
+
)
|
| 68 |
+
col_indices = torch.arange(input_ids.size(1)).unsqueeze(0)
|
| 69 |
+
attention_mask = col_indices < input_lengths.unsqueeze(1)
|
| 70 |
+
label_mask = torch.logical_or(col_indices < prompt_lengths.unsqueeze(1), ~attention_mask)
|
| 71 |
+
labels = input_ids.masked_fill(label_mask, -100)
|
| 72 |
+
if self.max_length is not None:
|
| 73 |
+
input_ids = input_ids[:, : self.max_length]
|
| 74 |
+
attention_mask = attention_mask[:, : self.max_length]
|
| 75 |
+
labels = labels[:, : self.max_length]
|
| 76 |
+
return {"input_ids": input_ids, "attention_mask": attention_mask, "labels": labels}
|
tasks/tasksmith-ecb1931929df/tests/source/examples/evaluation/lora-lm-eval.ipynb
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tasks/tasksmith-ecb1931929df/tests/source/examples/feature_extraction/peft_lora_embedding_semantic_search.py
ADDED
|
@@ -0,0 +1,502 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 logging
|
| 17 |
+
import math
|
| 18 |
+
import os
|
| 19 |
+
import random
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
|
| 22 |
+
import datasets
|
| 23 |
+
import evaluate
|
| 24 |
+
import torch
|
| 25 |
+
import transformers
|
| 26 |
+
from accelerate import Accelerator
|
| 27 |
+
from accelerate.logging import get_logger
|
| 28 |
+
from accelerate.utils import set_seed
|
| 29 |
+
from datasets import DatasetDict, load_dataset
|
| 30 |
+
from huggingface_hub import HfApi
|
| 31 |
+
from torch import nn
|
| 32 |
+
from torch.utils.data import DataLoader
|
| 33 |
+
from tqdm import tqdm
|
| 34 |
+
from transformers import AutoModel, AutoTokenizer, SchedulerType, default_data_collator, get_scheduler
|
| 35 |
+
|
| 36 |
+
from peft import LoraConfig, TaskType, get_peft_model
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
logger = get_logger(__name__)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def parse_args():
|
| 43 |
+
parser = argparse.ArgumentParser(description="Training a PEFT model for Semantic Search task")
|
| 44 |
+
parser.add_argument("--dataset_name", type=str, default=None, help="dataset name on HF hub")
|
| 45 |
+
parser.add_argument(
|
| 46 |
+
"--max_length",
|
| 47 |
+
type=int,
|
| 48 |
+
default=128,
|
| 49 |
+
help=(
|
| 50 |
+
"The maximum total input sequence length after tokenization. Sequences longer than this will be truncated,"
|
| 51 |
+
" sequences shorter will be padded if `--pad_to_max_length` is passed."
|
| 52 |
+
),
|
| 53 |
+
)
|
| 54 |
+
parser.add_argument(
|
| 55 |
+
"--model_name_or_path",
|
| 56 |
+
type=str,
|
| 57 |
+
help="Path to pretrained model or model identifier from huggingface.co/models.",
|
| 58 |
+
required=True,
|
| 59 |
+
)
|
| 60 |
+
parser.add_argument(
|
| 61 |
+
"--per_device_train_batch_size",
|
| 62 |
+
type=int,
|
| 63 |
+
default=8,
|
| 64 |
+
help="Batch size (per device) for the training dataloader.",
|
| 65 |
+
)
|
| 66 |
+
parser.add_argument(
|
| 67 |
+
"--per_device_eval_batch_size",
|
| 68 |
+
type=int,
|
| 69 |
+
default=8,
|
| 70 |
+
help="Batch size (per device) for the evaluation dataloader.",
|
| 71 |
+
)
|
| 72 |
+
parser.add_argument(
|
| 73 |
+
"--learning_rate",
|
| 74 |
+
type=float,
|
| 75 |
+
default=5e-5,
|
| 76 |
+
help="Initial learning rate (after the potential warmup period) to use.",
|
| 77 |
+
)
|
| 78 |
+
parser.add_argument("--weight_decay", type=float, default=0.0, help="Weight decay to use.")
|
| 79 |
+
parser.add_argument("--num_train_epochs", type=int, default=3, help="Total number of training epochs to perform.")
|
| 80 |
+
parser.add_argument(
|
| 81 |
+
"--max_train_steps",
|
| 82 |
+
type=int,
|
| 83 |
+
default=None,
|
| 84 |
+
help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
|
| 85 |
+
)
|
| 86 |
+
parser.add_argument(
|
| 87 |
+
"--gradient_accumulation_steps",
|
| 88 |
+
type=int,
|
| 89 |
+
default=1,
|
| 90 |
+
help="Number of updates steps to accumulate before performing a backward/update pass.",
|
| 91 |
+
)
|
| 92 |
+
parser.add_argument(
|
| 93 |
+
"--lr_scheduler_type",
|
| 94 |
+
type=SchedulerType,
|
| 95 |
+
default="linear",
|
| 96 |
+
help="The scheduler type to use.",
|
| 97 |
+
choices=["linear", "cosine", "cosine_with_restarts", "polynomial", "constant", "constant_with_warmup"],
|
| 98 |
+
)
|
| 99 |
+
parser.add_argument(
|
| 100 |
+
"--num_warmup_steps", type=int, default=0, help="Number of steps for the warmup in the lr scheduler."
|
| 101 |
+
)
|
| 102 |
+
parser.add_argument("--output_dir", type=str, default=None, help="Where to store the final model.")
|
| 103 |
+
parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
|
| 104 |
+
parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
|
| 105 |
+
parser.add_argument(
|
| 106 |
+
"--hub_model_id", type=str, help="The name of the repository to keep in sync with the local `output_dir`."
|
| 107 |
+
)
|
| 108 |
+
parser.add_argument("--hub_token", type=str, help="The token to use to push to the Model Hub.")
|
| 109 |
+
parser.add_argument(
|
| 110 |
+
"--checkpointing_steps",
|
| 111 |
+
type=str,
|
| 112 |
+
default=None,
|
| 113 |
+
help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.",
|
| 114 |
+
)
|
| 115 |
+
parser.add_argument(
|
| 116 |
+
"--resume_from_checkpoint",
|
| 117 |
+
type=str,
|
| 118 |
+
default=None,
|
| 119 |
+
help="If the training should continue from a checkpoint folder.",
|
| 120 |
+
)
|
| 121 |
+
parser.add_argument(
|
| 122 |
+
"--with_tracking",
|
| 123 |
+
action="store_true",
|
| 124 |
+
help="Whether to enable experiment trackers for logging.",
|
| 125 |
+
)
|
| 126 |
+
parser.add_argument(
|
| 127 |
+
"--report_to",
|
| 128 |
+
type=str,
|
| 129 |
+
default="all",
|
| 130 |
+
help=(
|
| 131 |
+
'The integration to report the results and logs to. Supported platforms are `"tensorboard"`,'
|
| 132 |
+
' `"wandb"`, `"comet_ml"` and `"clearml"`. Use `"all"` (default) to report to all integrations.'
|
| 133 |
+
"Only applicable when `--with_tracking` is passed."
|
| 134 |
+
),
|
| 135 |
+
)
|
| 136 |
+
parser.add_argument(
|
| 137 |
+
"--sanity_test",
|
| 138 |
+
action="store_true",
|
| 139 |
+
help="Whether to enable sanity test.",
|
| 140 |
+
)
|
| 141 |
+
parser.add_argument(
|
| 142 |
+
"--use_peft",
|
| 143 |
+
action="store_true",
|
| 144 |
+
help="Whether to use PEFT.",
|
| 145 |
+
)
|
| 146 |
+
args = parser.parse_args()
|
| 147 |
+
|
| 148 |
+
if args.push_to_hub:
|
| 149 |
+
assert args.output_dir is not None, "Need an `output_dir` to create a repo when `--push_to_hub` is passed."
|
| 150 |
+
|
| 151 |
+
return args
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def save_model_hook(models, weights, output_dir):
|
| 155 |
+
for i, model in enumerate(models):
|
| 156 |
+
model.save_pretrained(output_dir, state_dict=weights[i])
|
| 157 |
+
# make sure to pop weight so that corresponding model is not saved again
|
| 158 |
+
weights.pop()
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def load_model_hook(models, input_dir):
|
| 162 |
+
while len(models) > 0:
|
| 163 |
+
model = models.pop()
|
| 164 |
+
# pop models so that they are not loaded again
|
| 165 |
+
if hasattr(model, "active_adapter") and hasattr(model, "load_adapter"):
|
| 166 |
+
model.load_adapter(input_dir, model.active_adapter, is_trainable=True)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class AutoModelForSentenceEmbedding(nn.Module):
|
| 170 |
+
def __init__(self, model_name, tokenizer, normalize=True):
|
| 171 |
+
super().__init__()
|
| 172 |
+
|
| 173 |
+
self.model = AutoModel.from_pretrained(
|
| 174 |
+
model_name
|
| 175 |
+
) # , quantizaton_config=BitsAndBytesConfig(load_in_8bit=True), device_map={"":0})
|
| 176 |
+
self.normalize = normalize
|
| 177 |
+
self.tokenizer = tokenizer
|
| 178 |
+
|
| 179 |
+
def forward(self, **kwargs):
|
| 180 |
+
model_output = self.model(**kwargs)
|
| 181 |
+
embeddings = self.mean_pooling(model_output, kwargs["attention_mask"])
|
| 182 |
+
if self.normalize:
|
| 183 |
+
embeddings = torch.nn.functional.normalize(embeddings, p=2, dim=1)
|
| 184 |
+
|
| 185 |
+
return embeddings
|
| 186 |
+
|
| 187 |
+
def mean_pooling(self, model_output, attention_mask):
|
| 188 |
+
token_embeddings = model_output[0] # First element of model_output contains all token embeddings
|
| 189 |
+
input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
|
| 190 |
+
return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
|
| 191 |
+
|
| 192 |
+
def __getattr__(self, name: str):
|
| 193 |
+
"""Forward missing attributes to the wrapped module."""
|
| 194 |
+
try:
|
| 195 |
+
return super().__getattr__(name) # defer to nn.Module's logic
|
| 196 |
+
except AttributeError:
|
| 197 |
+
if name == "model": # see #1892: prevent infinite recursion if class is not initialized
|
| 198 |
+
raise
|
| 199 |
+
return getattr(self.model, name)
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def get_cosing_embeddings(query_embs, product_embs):
|
| 203 |
+
return torch.sum(query_embs * product_embs, axis=1)
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def get_loss(cosine_score, labels):
|
| 207 |
+
return torch.mean(torch.square(labels * (1 - cosine_score) + torch.clamp((1 - labels) * cosine_score, min=0.0)))
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def main():
|
| 211 |
+
args = parse_args()
|
| 212 |
+
|
| 213 |
+
accelerator_kwargs = {"gradient_accumulation_steps": args.gradient_accumulation_steps}
|
| 214 |
+
if args.with_tracking:
|
| 215 |
+
accelerator_kwargs["log_with"] = args.report_to
|
| 216 |
+
accelerator_kwargs["project_dir"] = args.output_dir
|
| 217 |
+
accelerator = Accelerator(**accelerator_kwargs)
|
| 218 |
+
|
| 219 |
+
# Make one log on every process with the configuration for debugging.
|
| 220 |
+
logging.basicConfig(
|
| 221 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
| 222 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
| 223 |
+
level=logging.INFO,
|
| 224 |
+
)
|
| 225 |
+
logger.info(accelerator.state, main_process_only=False)
|
| 226 |
+
if accelerator.is_local_main_process:
|
| 227 |
+
datasets.utils.logging.set_verbosity_warning()
|
| 228 |
+
transformers.utils.logging.set_verbosity_info()
|
| 229 |
+
else:
|
| 230 |
+
datasets.utils.logging.set_verbosity_error()
|
| 231 |
+
transformers.utils.logging.set_verbosity_error()
|
| 232 |
+
|
| 233 |
+
# If passed along, set the training seed now.
|
| 234 |
+
if args.seed is not None:
|
| 235 |
+
set_seed(args.seed)
|
| 236 |
+
|
| 237 |
+
# Handle the repository creation
|
| 238 |
+
if accelerator.is_main_process:
|
| 239 |
+
if args.push_to_hub:
|
| 240 |
+
api = HfApi(token=args.hub_token)
|
| 241 |
+
|
| 242 |
+
# Create repo (repo_name from args or inferred)
|
| 243 |
+
repo_name = args.hub_model_id
|
| 244 |
+
if repo_name is None:
|
| 245 |
+
repo_name = Path(args.output_dir).absolute().name
|
| 246 |
+
repo_id = api.create_repo(repo_name, exist_ok=True).repo_id
|
| 247 |
+
|
| 248 |
+
with open(os.path.join(args.output_dir, ".gitignore"), "w+") as gitignore:
|
| 249 |
+
if "step_*" not in gitignore:
|
| 250 |
+
gitignore.write("step_*\n")
|
| 251 |
+
if "epoch_*" not in gitignore:
|
| 252 |
+
gitignore.write("epoch_*\n")
|
| 253 |
+
elif args.output_dir is not None:
|
| 254 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 255 |
+
accelerator.wait_for_everyone()
|
| 256 |
+
|
| 257 |
+
# get the tokenizer
|
| 258 |
+
tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path)
|
| 259 |
+
|
| 260 |
+
# dataset download and preprocessing
|
| 261 |
+
if args.sanity_test:
|
| 262 |
+
train_dataset = load_dataset("smangrul/amazon_esci", split="train[:1024]")
|
| 263 |
+
val_dataset = load_dataset("smangrul/amazon_esci", split="validation[:1024]")
|
| 264 |
+
|
| 265 |
+
dataset = DatasetDict({"train": train_dataset, "validation": val_dataset})
|
| 266 |
+
else:
|
| 267 |
+
dataset = load_dataset(args.dataset_name, revision="main")
|
| 268 |
+
|
| 269 |
+
def preprocess_function(examples):
|
| 270 |
+
queries = examples["query"]
|
| 271 |
+
result = tokenizer(queries, padding="max_length", max_length=70, truncation=True)
|
| 272 |
+
result = {f"query_{k}": v for k, v in result.items()}
|
| 273 |
+
|
| 274 |
+
products = examples["product_title"]
|
| 275 |
+
result_products = tokenizer(products, padding="max_length", max_length=70, truncation=True)
|
| 276 |
+
for k, v in result_products.items():
|
| 277 |
+
result[f"product_{k}"] = v
|
| 278 |
+
|
| 279 |
+
result["labels"] = examples["relevance_label"]
|
| 280 |
+
return result
|
| 281 |
+
|
| 282 |
+
processed_datasets = dataset.map(
|
| 283 |
+
preprocess_function,
|
| 284 |
+
batched=True,
|
| 285 |
+
remove_columns=dataset["train"].column_names,
|
| 286 |
+
desc="Running tokenizer on dataset",
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
# Log a few random samples from the training set:
|
| 290 |
+
for index in random.sample(range(len(processed_datasets["train"])), 3):
|
| 291 |
+
logger.info(f"Sample {index} of the training set: {processed_datasets['train'][index]}.")
|
| 292 |
+
|
| 293 |
+
# base model
|
| 294 |
+
model = AutoModelForSentenceEmbedding(args.model_name_or_path, tokenizer)
|
| 295 |
+
|
| 296 |
+
if args.use_peft:
|
| 297 |
+
# peft config and wrapping
|
| 298 |
+
peft_config = LoraConfig(
|
| 299 |
+
r=8,
|
| 300 |
+
lora_alpha=16,
|
| 301 |
+
bias="none",
|
| 302 |
+
task_type=TaskType.FEATURE_EXTRACTION,
|
| 303 |
+
target_modules=["key", "query", "value"],
|
| 304 |
+
)
|
| 305 |
+
model = get_peft_model(model, peft_config)
|
| 306 |
+
model.print_trainable_parameters()
|
| 307 |
+
|
| 308 |
+
accelerator.print(model)
|
| 309 |
+
|
| 310 |
+
# get dataloaders
|
| 311 |
+
train_dataloader = DataLoader(
|
| 312 |
+
processed_datasets["train"],
|
| 313 |
+
shuffle=True,
|
| 314 |
+
collate_fn=default_data_collator,
|
| 315 |
+
batch_size=args.per_device_train_batch_size,
|
| 316 |
+
pin_memory=True,
|
| 317 |
+
)
|
| 318 |
+
|
| 319 |
+
eval_dataloader = DataLoader(
|
| 320 |
+
processed_datasets["validation"],
|
| 321 |
+
shuffle=False,
|
| 322 |
+
collate_fn=default_data_collator,
|
| 323 |
+
batch_size=args.per_device_eval_batch_size,
|
| 324 |
+
pin_memory=True,
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
optimizer = torch.optim.Adam(model.parameters(), lr=args.learning_rate)
|
| 328 |
+
|
| 329 |
+
# Scheduler and math around the number of training steps.
|
| 330 |
+
overrode_max_train_steps = False
|
| 331 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
| 332 |
+
if args.max_train_steps is None:
|
| 333 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 334 |
+
overrode_max_train_steps = True
|
| 335 |
+
|
| 336 |
+
lr_scheduler = get_scheduler(
|
| 337 |
+
name=args.lr_scheduler_type,
|
| 338 |
+
optimizer=optimizer,
|
| 339 |
+
num_warmup_steps=args.num_warmup_steps,
|
| 340 |
+
num_training_steps=args.max_train_steps,
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
# Prepare everything with our `accelerator`.
|
| 344 |
+
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
|
| 345 |
+
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
|
| 346 |
+
)
|
| 347 |
+
|
| 348 |
+
# We need to recalculate our total training steps as the size of the training dataloader may have changed
|
| 349 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
| 350 |
+
if overrode_max_train_steps:
|
| 351 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 352 |
+
# Afterwards we recalculate our number of training epochs
|
| 353 |
+
args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
|
| 354 |
+
|
| 355 |
+
# Figure out how many steps we should save the Accelerator states
|
| 356 |
+
checkpointing_steps = args.checkpointing_steps
|
| 357 |
+
if checkpointing_steps is not None and checkpointing_steps.isdigit():
|
| 358 |
+
checkpointing_steps = int(checkpointing_steps)
|
| 359 |
+
|
| 360 |
+
# We need to initialize the trackers we use, and also store our configuration.
|
| 361 |
+
# The trackers initializes automatically on the main process.
|
| 362 |
+
if args.with_tracking:
|
| 363 |
+
experiment_config = vars(args)
|
| 364 |
+
# TensorBoard cannot log Enums, need the raw value
|
| 365 |
+
experiment_config["lr_scheduler_type"] = experiment_config["lr_scheduler_type"].value
|
| 366 |
+
accelerator.init_trackers("peft_semantic_search", experiment_config)
|
| 367 |
+
|
| 368 |
+
metric = evaluate.load("roc_auc")
|
| 369 |
+
|
| 370 |
+
total_batch_size = args.per_device_train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
|
| 371 |
+
|
| 372 |
+
if args.use_peft:
|
| 373 |
+
# saving and loading checkpoints for resuming training
|
| 374 |
+
accelerator.register_save_state_pre_hook(save_model_hook)
|
| 375 |
+
accelerator.register_load_state_pre_hook(load_model_hook)
|
| 376 |
+
|
| 377 |
+
logger.info("***** Running training *****")
|
| 378 |
+
logger.info(f" Num examples = {len(processed_datasets['train'])}")
|
| 379 |
+
logger.info(f" Num Epochs = {args.num_train_epochs}")
|
| 380 |
+
logger.info(f" Instantaneous batch size per device = {args.per_device_train_batch_size}")
|
| 381 |
+
logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
|
| 382 |
+
logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
|
| 383 |
+
logger.info(f" Total optimization steps = {args.max_train_steps}")
|
| 384 |
+
|
| 385 |
+
# Only show the progress bar once on each machine.
|
| 386 |
+
progress_bar = tqdm(range(args.max_train_steps), disable=not accelerator.is_local_main_process)
|
| 387 |
+
completed_steps = 0
|
| 388 |
+
starting_epoch = 0
|
| 389 |
+
# Potentially load in the weights and states from a previous save
|
| 390 |
+
if args.resume_from_checkpoint:
|
| 391 |
+
if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
|
| 392 |
+
accelerator.print(f"Resumed from checkpoint: {args.resume_from_checkpoint}")
|
| 393 |
+
accelerator.load_state(args.resume_from_checkpoint)
|
| 394 |
+
path = os.path.basename(args.resume_from_checkpoint)
|
| 395 |
+
else:
|
| 396 |
+
# Get the most recent checkpoint
|
| 397 |
+
dirs = [f.name for f in os.scandir(os.getcwd()) if f.is_dir()]
|
| 398 |
+
dirs.sort(key=os.path.getctime)
|
| 399 |
+
path = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last
|
| 400 |
+
# Extract `epoch_{i}` or `step_{i}`
|
| 401 |
+
training_difference = os.path.splitext(path)[0]
|
| 402 |
+
|
| 403 |
+
if "epoch" in training_difference:
|
| 404 |
+
starting_epoch = int(training_difference.replace("epoch_", "")) + 1
|
| 405 |
+
resume_step = None
|
| 406 |
+
completed_steps = starting_epoch * num_update_steps_per_epoch
|
| 407 |
+
else:
|
| 408 |
+
# need to multiply `gradient_accumulation_steps` to reflect real steps
|
| 409 |
+
resume_step = int(training_difference.replace("step_", "")) * args.gradient_accumulation_steps
|
| 410 |
+
starting_epoch = resume_step // len(train_dataloader)
|
| 411 |
+
resume_step -= starting_epoch * len(train_dataloader)
|
| 412 |
+
completed_steps = resume_step // args.gradient_accumulation_steps
|
| 413 |
+
|
| 414 |
+
# update the progress_bar if load from checkpoint
|
| 415 |
+
progress_bar.update(completed_steps)
|
| 416 |
+
|
| 417 |
+
for epoch in range(starting_epoch, args.num_train_epochs):
|
| 418 |
+
model.train()
|
| 419 |
+
total_loss = 0
|
| 420 |
+
if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None:
|
| 421 |
+
# We skip the first `n` batches in the dataloader when resuming from a checkpoint
|
| 422 |
+
active_dataloader = accelerator.skip_first_batches(train_dataloader, resume_step)
|
| 423 |
+
else:
|
| 424 |
+
active_dataloader = train_dataloader
|
| 425 |
+
for step, batch in enumerate(active_dataloader):
|
| 426 |
+
with accelerator.accumulate(model):
|
| 427 |
+
query_embs = model(**{k.replace("query_", ""): v for k, v in batch.items() if "query" in k})
|
| 428 |
+
product_embs = model(**{k.replace("product_", ""): v for k, v in batch.items() if "product" in k})
|
| 429 |
+
loss = get_loss(get_cosing_embeddings(query_embs, product_embs), batch["labels"])
|
| 430 |
+
total_loss += accelerator.reduce(loss.detach().float(), reduction="sum")
|
| 431 |
+
accelerator.backward(loss)
|
| 432 |
+
optimizer.step()
|
| 433 |
+
lr_scheduler.step()
|
| 434 |
+
model.zero_grad()
|
| 435 |
+
|
| 436 |
+
# Checks if the accelerator has performed an optimization step behind the scenes
|
| 437 |
+
if accelerator.sync_gradients:
|
| 438 |
+
progress_bar.update(1)
|
| 439 |
+
completed_steps += 1
|
| 440 |
+
|
| 441 |
+
if (step + 1) % 100 == 0:
|
| 442 |
+
logger.info(f"Step: {step + 1}, Loss: {total_loss / (step + 1)}")
|
| 443 |
+
if args.with_tracking:
|
| 444 |
+
accelerator.log({"train/loss": total_loss / (step + 1)}, step=completed_steps)
|
| 445 |
+
|
| 446 |
+
if isinstance(checkpointing_steps, int):
|
| 447 |
+
if completed_steps % checkpointing_steps == 0:
|
| 448 |
+
output_dir = f"step_{completed_steps}"
|
| 449 |
+
if args.output_dir is not None:
|
| 450 |
+
output_dir = os.path.join(args.output_dir, output_dir)
|
| 451 |
+
accelerator.save_state(output_dir)
|
| 452 |
+
|
| 453 |
+
if completed_steps >= args.max_train_steps:
|
| 454 |
+
break
|
| 455 |
+
|
| 456 |
+
model.eval()
|
| 457 |
+
for step, batch in enumerate(eval_dataloader):
|
| 458 |
+
with torch.no_grad():
|
| 459 |
+
query_embs = model(**{k.replace("query_", ""): v for k, v in batch.items() if "query" in k})
|
| 460 |
+
product_embs = model(**{k.replace("product_", ""): v for k, v in batch.items() if "product" in k})
|
| 461 |
+
prediction_scores = get_cosing_embeddings(query_embs, product_embs)
|
| 462 |
+
prediction_scores, references = accelerator.gather_for_metrics((prediction_scores, batch["labels"]))
|
| 463 |
+
metric.add_batch(
|
| 464 |
+
prediction_scores=prediction_scores,
|
| 465 |
+
references=references,
|
| 466 |
+
)
|
| 467 |
+
|
| 468 |
+
result = metric.compute()
|
| 469 |
+
result = {f"eval/{k}": v for k, v in result.items()}
|
| 470 |
+
# Use accelerator.print to print only on the main process.
|
| 471 |
+
accelerator.print(f"epoch {epoch}:", result)
|
| 472 |
+
if args.with_tracking:
|
| 473 |
+
result["train/epoch_loss"] = total_loss.item() / len(train_dataloader)
|
| 474 |
+
accelerator.log(result, step=completed_steps)
|
| 475 |
+
|
| 476 |
+
if args.output_dir is not None:
|
| 477 |
+
accelerator.wait_for_everyone()
|
| 478 |
+
if accelerator.is_main_process:
|
| 479 |
+
if isinstance(checkpointing_steps, str):
|
| 480 |
+
accelerator.save_state(os.path.join(args.output_dir, f"epoch_{epoch}"))
|
| 481 |
+
accelerator.unwrap_model(model).save_pretrained(
|
| 482 |
+
args.output_dir, state_dict=accelerator.get_state_dict(accelerator.unwrap_model(model))
|
| 483 |
+
)
|
| 484 |
+
tokenizer.save_pretrained(args.output_dir)
|
| 485 |
+
if args.push_to_hub:
|
| 486 |
+
commit_message = (
|
| 487 |
+
f"Training in progress epoch {epoch}"
|
| 488 |
+
if epoch < args.num_train_epochs - 1
|
| 489 |
+
else "End of training"
|
| 490 |
+
)
|
| 491 |
+
api.upload_folder(
|
| 492 |
+
repo_id=repo_id,
|
| 493 |
+
folder_path=args.output_dir,
|
| 494 |
+
commit_message=commit_message,
|
| 495 |
+
run_as_future=True,
|
| 496 |
+
)
|
| 497 |
+
accelerator.wait_for_everyone()
|
| 498 |
+
accelerator.end_training()
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
if __name__ == "__main__":
|
| 502 |
+
main()
|
tasks/tasksmith-ecb1931929df/tests/source/examples/feature_extraction/peft_lora_embedding_semantic_similarity_inference.ipynb
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tasks/tasksmith-ecb1931929df/tests/source/examples/feature_extraction/requirements.txt
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
peft
|
| 2 |
+
accelerate
|
| 3 |
+
transformers
|
| 4 |
+
datasets==2.18.0
|
| 5 |
+
evaluate
|
| 6 |
+
hnswlib
|
| 7 |
+
pandas
|
| 8 |
+
tqdm
|
| 9 |
+
huggingface_hub
|
| 10 |
+
wandb
|
tasks/tasksmith-ecb1931929df/tests/source/examples/fp4_finetuning/finetune_fp4_opt_bnb_peft.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
import transformers
|
| 6 |
+
from datasets import load_dataset
|
| 7 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
|
| 8 |
+
|
| 9 |
+
from peft import LoraConfig, get_peft_model
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = "0" # force to use CUDA GPU device 0
|
| 13 |
+
os.environ["ZE_AFFINITY_MASK"] = "0" # force to use Intel XPU device 0
|
| 14 |
+
# -*- coding: utf-8 -*-
|
| 15 |
+
"""Finetune-opt-bnb-peft.ipynb
|
| 16 |
+
|
| 17 |
+
Automatically generated by Colaboratory.
|
| 18 |
+
|
| 19 |
+
Original file is located at
|
| 20 |
+
https://colab.research.google.com/drive/1jCkpikz0J2o20FBQmYmAGdiKmJGOMo-o
|
| 21 |
+
|
| 22 |
+
## Fine-tune large models using 🤗 `peft` adapters, `transformers` & `bitsandbytes`
|
| 23 |
+
|
| 24 |
+
In this tutorial we will cover how we can fine-tune large language models using the very recent `peft` library and `bitsandbytes` for loading large models in 8-bit.
|
| 25 |
+
The fine-tuning method will rely on a recent method called "Low Rank Adapters" (LoRA), instead of fine-tuning the entire model you just have to fine-tune these adapters and load them properly inside the model.
|
| 26 |
+
After fine-tuning the model you can also share your adapters on the 🤗 Hub and load them very easily. Let's get started!
|
| 27 |
+
|
| 28 |
+
### Install requirements
|
| 29 |
+
|
| 30 |
+
First, run the cells below to install the requirements:
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
"""### Model loading
|
| 35 |
+
|
| 36 |
+
Here let's load the `opt-6.7b` model, its weights in half-precision (float16) are about 13GB on the Hub! If we load them in 8-bit we would require around 7GB of memory instead.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
device_type = torch.accelerator.current_accelerator().type if hasattr(torch, "accelerator") else "cuda"
|
| 40 |
+
device_module = getattr(torch, device_type, torch.cuda)
|
| 41 |
+
free_in_GB = int(device_module.mem_get_info()[0] / 1024**3)
|
| 42 |
+
max_memory = f"{free_in_GB - 2}GB"
|
| 43 |
+
|
| 44 |
+
n_gpus = device_module.device_count()
|
| 45 |
+
max_memory = {i: max_memory for i in range(n_gpus)}
|
| 46 |
+
|
| 47 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 48 |
+
"facebook/opt-350m",
|
| 49 |
+
max_memory=max_memory,
|
| 50 |
+
quantization_config=BitsAndBytesConfig(
|
| 51 |
+
load_in_4bit=True,
|
| 52 |
+
llm_int8_threshold=6.0,
|
| 53 |
+
llm_int8_has_fp16_weight=False,
|
| 54 |
+
bnb_4bit_compute_dtype=torch.float16,
|
| 55 |
+
bnb_4bit_use_double_quant=True,
|
| 56 |
+
bnb_4bit_quant_type="nf4",
|
| 57 |
+
),
|
| 58 |
+
dtype=torch.float16,
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m")
|
| 62 |
+
|
| 63 |
+
"""### Post-processing on the model
|
| 64 |
+
|
| 65 |
+
Finally, we need to apply some post-processing on the 8-bit model to enable training, let's freeze all our layers, and cast the layer-norm in `float32` for stability. We also cast the output of the last layer in `float32` for the same reasons.
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
print(model)
|
| 69 |
+
|
| 70 |
+
for param in model.parameters():
|
| 71 |
+
param.requires_grad = False # freeze the model - train adapters later
|
| 72 |
+
if param.ndim == 1:
|
| 73 |
+
# cast the small parameters (e.g. layernorm) to fp32 for stability
|
| 74 |
+
param.data = param.data.to(torch.float32)
|
| 75 |
+
|
| 76 |
+
# model.gradient_checkpointing_enable() # reduce number of stored activations
|
| 77 |
+
# model.model.decoder.project_in = lambda x: x.requires_grad_(True)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class CastOutputToFloat(nn.Sequential):
|
| 81 |
+
def forward(self, x):
|
| 82 |
+
return super().forward(x).to(torch.float32)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
model.lm_head = CastOutputToFloat(model.lm_head)
|
| 86 |
+
|
| 87 |
+
"""### Apply LoRA
|
| 88 |
+
|
| 89 |
+
Here comes the magic with `peft`! Let's load a `PeftModel` and specify that we are going to use low-rank adapters (LoRA) using `get_peft_model` utility function from `peft`.
|
| 90 |
+
"""
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def print_trainable_parameters(model):
|
| 94 |
+
"""
|
| 95 |
+
Prints the number of trainable parameters in the model.
|
| 96 |
+
"""
|
| 97 |
+
trainable_params = 0
|
| 98 |
+
all_param = 0
|
| 99 |
+
for _, param in model.named_parameters():
|
| 100 |
+
all_param += param.numel()
|
| 101 |
+
if param.requires_grad:
|
| 102 |
+
trainable_params += param.numel()
|
| 103 |
+
print(
|
| 104 |
+
f"trainable params: {trainable_params} || all params: {all_param} || trainable%: {100 * trainable_params / all_param}"
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
config = LoraConfig(
|
| 109 |
+
r=64,
|
| 110 |
+
lora_alpha=32,
|
| 111 |
+
target_modules=["q_proj", "v_proj", "out_proj", "fc1", "fc2"],
|
| 112 |
+
lora_dropout=0.01,
|
| 113 |
+
bias="none",
|
| 114 |
+
task_type="CAUSAL_LM",
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
model = get_peft_model(model, config)
|
| 118 |
+
print_trainable_parameters(model)
|
| 119 |
+
|
| 120 |
+
# Verifying the datatypes.
|
| 121 |
+
dtypes = {}
|
| 122 |
+
for _, p in model.named_parameters():
|
| 123 |
+
dtype = p.dtype
|
| 124 |
+
if dtype not in dtypes:
|
| 125 |
+
dtypes[dtype] = 0
|
| 126 |
+
dtypes[dtype] += p.numel()
|
| 127 |
+
total = 0
|
| 128 |
+
for k, v in dtypes.items():
|
| 129 |
+
total += v
|
| 130 |
+
for k, v in dtypes.items():
|
| 131 |
+
print(k, v, v / total)
|
| 132 |
+
|
| 133 |
+
"""### Training"""
|
| 134 |
+
|
| 135 |
+
data = load_dataset("Abirate/english_quotes")
|
| 136 |
+
data = data.map(lambda samples: tokenizer(samples["quote"]), batched=True)
|
| 137 |
+
|
| 138 |
+
trainer = transformers.Trainer(
|
| 139 |
+
model=model,
|
| 140 |
+
train_dataset=data["train"],
|
| 141 |
+
args=transformers.TrainingArguments(
|
| 142 |
+
per_device_train_batch_size=4,
|
| 143 |
+
gradient_accumulation_steps=4,
|
| 144 |
+
warmup_steps=10,
|
| 145 |
+
max_steps=20,
|
| 146 |
+
learning_rate=3e-4,
|
| 147 |
+
fp16=True,
|
| 148 |
+
logging_steps=1,
|
| 149 |
+
output_dir="outputs",
|
| 150 |
+
),
|
| 151 |
+
data_collator=transformers.DataCollatorForLanguageModeling(tokenizer, mlm=False),
|
| 152 |
+
)
|
| 153 |
+
model.config.use_cache = False # silence the warnings. Please re-enable for inference!
|
| 154 |
+
trainer.train()
|
| 155 |
+
|
| 156 |
+
# from huggingface_hub import notebook_login
|
| 157 |
+
|
| 158 |
+
# notebook_login()
|
| 159 |
+
|
| 160 |
+
# model.push_to_hub("ybelkada/opt-6.7b-lora", use_auth_token=True)
|
| 161 |
+
|
| 162 |
+
"""## Load adapters from the Hub
|
| 163 |
+
|
| 164 |
+
You can also directly load adapters from the Hub using the commands below:
|
| 165 |
+
"""
|
| 166 |
+
|
| 167 |
+
# import torch
|
| 168 |
+
# from peft import PeftModel, PeftConfig
|
| 169 |
+
# from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
|
| 170 |
+
#
|
| 171 |
+
# peft_model_id = "ybelkada/opt-6.7b-lora"
|
| 172 |
+
# config = PeftConfig.from_pretrained(peft_model_id)
|
| 173 |
+
# model = AutoModelForCausalLM.from_pretrained(config.base_model_name_or_path, return_dict=True, quantization_config=BitsAndBytesConfig(load_in_8bit=True), device_map='auto')
|
| 174 |
+
# tokenizer = AutoTokenizer.from_pretrained(config.base_model_name_or_path)
|
| 175 |
+
#
|
| 176 |
+
## Load the Lora model
|
| 177 |
+
# model = PeftModel.from_pretrained(model, peft_model_id)
|
| 178 |
+
#
|
| 179 |
+
# """## Inference
|
| 180 |
+
#
|
| 181 |
+
# You can then directly use the trained model or the model that you have loaded from the 🤗 Hub for inference as you would do it usually in `transformers`.
|
| 182 |
+
# """
|
| 183 |
+
#
|
| 184 |
+
batch = tokenizer("Two things are infinite: ", return_tensors="pt").to(model.device)
|
| 185 |
+
|
| 186 |
+
model.config.use_cache = False # silence the warnings. Please re-enable for inference!
|
| 187 |
+
model.eval()
|
| 188 |
+
|
| 189 |
+
with torch.amp.autocast(device_type=device_type):
|
| 190 |
+
output_tokens = model.generate(**batch, max_new_tokens=50)
|
| 191 |
+
|
| 192 |
+
print("\n\n", tokenizer.decode(output_tokens[0], skip_special_tokens=True))
|
| 193 |
+
# model.save('./test.pt')
|
| 194 |
+
|
| 195 |
+
# """As you can see by fine-tuning for few steps we have almost recovered the quote from Albert Einstein that is present in the [training data](https://huggingface.co/datasets/Abirate/english_quotes)."""
|
tasks/tasksmith-ecb1931929df/tests/source/examples/gralora_finetuning/README.md
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# GraLoRA: Granular Low-Rank Adaptation
|
| 2 |
+
|
| 3 |
+

|
| 4 |
+
|
| 5 |
+
## Introduction
|
| 6 |
+
[**Granular Low-Rank Adaptation (GraLoRA)**](https://huggingface.co/papers/2505.20355) is a PEFT method designed to enhance the **expressivity** of low-rank adaptation while improving **robustness to outlier** activations, based on insights from well-known issues in quantization.
|
| 7 |
+
|
| 8 |
+
GraLoRA introduces a structured and fine-grained adaptation scheme. It divides the adaptation space into a grid of $𝑘^2$ smaller, independent adapter pairs, each responsible for a localized subset of the input and output dimensions.
|
| 9 |
+
|
| 10 |
+
## Quick start
|
| 11 |
+
|
| 12 |
+
With respect to your standard PEFT training procedure with LoRA, simply swap your `LoraConfig` for a `GraloraConfig`.
|
| 13 |
+
|
| 14 |
+
```python
|
| 15 |
+
import torch
|
| 16 |
+
from datasets import load_dataset
|
| 17 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 18 |
+
from trl import SFTTrainer, SFTConfig
|
| 19 |
+
from peft import GraloraConfig
|
| 20 |
+
|
| 21 |
+
model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.2-3B", dtype=torch.bfloat16, device_map="auto")
|
| 22 |
+
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.2-3B")
|
| 23 |
+
dataset = load_dataset("timdettmers/openassistant-guanaco", split="train")
|
| 24 |
+
gralora_config = GraloraConfig()
|
| 25 |
+
|
| 26 |
+
trainer = SFTTrainer(
|
| 27 |
+
model=model,
|
| 28 |
+
train_dataset=dataset,
|
| 29 |
+
processing_class=tokenizer,
|
| 30 |
+
peft_config=gralora_config,
|
| 31 |
+
args=SFTConfig(
|
| 32 |
+
max_length=2048,
|
| 33 |
+
dataset_text_field="text",
|
| 34 |
+
per_device_train_batch_size=2,
|
| 35 |
+
),
|
| 36 |
+
)
|
| 37 |
+
trainer.train()
|
| 38 |
+
trainer.model.save_pretrained("gralora-llama-3.2-3b")
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
Run the finetuning script simply by running:
|
| 42 |
+
```sh
|
| 43 |
+
python examples/gralora_finetuning/gralora_finetuning.py --base_model meta-llama/Meta-Llama-3-8B --data_path timdettmers/openassistant-guanaco
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
## Use the model on 🤗
|
| 47 |
+
You can load and use the model as any other 🤗 models.
|
| 48 |
+
```python
|
| 49 |
+
import torch
|
| 50 |
+
from peft import PeftModel
|
| 51 |
+
from transformers import AutoModelForCausalLM
|
| 52 |
+
|
| 53 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 54 |
+
"meta-llama/Meta-Llama-3-8B", dtype=torch.bfloat16, device_map="auto"
|
| 55 |
+
)
|
| 56 |
+
peft_model = PeftModel.from_pretrained(model, "gralora-llama-3-8b")
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
## Additional Notes
|
| 60 |
+
While `gralora_k` is set to 2 for default, you can increase this value to create more fine-grained adapters. `gralora_k` of 4 is recommended when the total rank (`r + hybrid_r`) is 64 or higher.
|
| 61 |
+
|
| 62 |
+
## Citation
|
| 63 |
+
```
|
| 64 |
+
@misc{jung2025graloragranularlowrankadaptation,
|
| 65 |
+
title={GraLoRA: Granular Low-Rank Adaptation for Parameter-Efficient Fine-Tuning},
|
| 66 |
+
author={Yeonjoon Jung and Daehyun Ahn and Hyungjun Kim and Taesu Kim and Eunhyeok Park},
|
| 67 |
+
year={2025},
|
| 68 |
+
eprint={2505.20355},
|
| 69 |
+
archivePrefix={arXiv},
|
| 70 |
+
primaryClass={cs.LG},
|
| 71 |
+
url={https://arxiv.org/abs/2505.20355},
|
| 72 |
+
}
|
| 73 |
+
```
|
tasks/tasksmith-ecb1931929df/tests/source/examples/gralora_finetuning/gralora_finetuning.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This script is based on examples/dora_finetuning/dora_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 GraloraConfig, 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 |
+
gralora_r: int,
|
| 30 |
+
gralora_alpha: int,
|
| 31 |
+
gralora_dropout: float,
|
| 32 |
+
gralora_target_modules: str,
|
| 33 |
+
gralora_k: int,
|
| 34 |
+
hybrid_r: int,
|
| 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 |
+
# GraLoRA config for the PEFT model
|
| 53 |
+
gralora_config = GraloraConfig(
|
| 54 |
+
r=gralora_r, # Rank of matrix
|
| 55 |
+
alpha=gralora_alpha,
|
| 56 |
+
target_modules=(
|
| 57 |
+
gralora_target_modules.split(",")
|
| 58 |
+
if gralora_target_modules
|
| 59 |
+
else ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
|
| 60 |
+
),
|
| 61 |
+
gralora_dropout=gralora_dropout,
|
| 62 |
+
gralora_k=gralora_k,
|
| 63 |
+
hybrid_r=hybrid_r,
|
| 64 |
+
bias="none",
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
# get the peft model with GraLoRA config
|
| 68 |
+
model = get_peft_model(model, gralora_config)
|
| 69 |
+
|
| 70 |
+
model.to(device) # MODEL TO GPU/CUDA
|
| 71 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 72 |
+
|
| 73 |
+
# Load the dataset
|
| 74 |
+
dataset = load_dataset(data_path)
|
| 75 |
+
|
| 76 |
+
def tokenize_function(examples):
|
| 77 |
+
inputs = tokenizer(examples["text"], padding="max_length", truncation=True, max_length=cutoff_len)
|
| 78 |
+
inputs["labels"] = inputs["input_ids"].copy() # setting labels for a language modeling task
|
| 79 |
+
return inputs
|
| 80 |
+
|
| 81 |
+
# Tokenize the dataset and prepare for training
|
| 82 |
+
tokenized_datasets = dataset.map(tokenize_function, batched=True, remove_columns=dataset["train"].column_names)
|
| 83 |
+
|
| 84 |
+
# Data collator to dynamically pad the batched examples
|
| 85 |
+
data_collator = DataCollatorForLanguageModeling(tokenizer, mlm=False)
|
| 86 |
+
|
| 87 |
+
# Define training arguments
|
| 88 |
+
training_args = TrainingArguments(
|
| 89 |
+
output_dir=output_dir,
|
| 90 |
+
num_train_epochs=num_epochs,
|
| 91 |
+
per_device_train_batch_size=batch_size,
|
| 92 |
+
per_device_eval_batch_size=batch_size,
|
| 93 |
+
warmup_steps=100,
|
| 94 |
+
weight_decay=0.01,
|
| 95 |
+
logging_steps=eval_step,
|
| 96 |
+
save_steps=save_step,
|
| 97 |
+
save_total_limit=2,
|
| 98 |
+
push_to_hub=push_to_hub,
|
| 99 |
+
hub_model_id=hub_model_id,
|
| 100 |
+
gradient_accumulation_steps=16,
|
| 101 |
+
fp16=True,
|
| 102 |
+
learning_rate=learning_rate,
|
| 103 |
+
hub_token=hf_token,
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
# Clear device cache to free memory
|
| 107 |
+
if torch.cuda.is_available():
|
| 108 |
+
torch.cuda.empty_cache()
|
| 109 |
+
elif torch.xpu.is_available():
|
| 110 |
+
torch.xpu.empty_cache()
|
| 111 |
+
|
| 112 |
+
# Initialize the Trainer
|
| 113 |
+
trainer = Trainer(
|
| 114 |
+
model=model,
|
| 115 |
+
args=training_args,
|
| 116 |
+
train_dataset=tokenized_datasets["train"],
|
| 117 |
+
eval_dataset=tokenized_datasets["test"],
|
| 118 |
+
data_collator=data_collator,
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
# Start model training
|
| 122 |
+
trainer.train()
|
| 123 |
+
|
| 124 |
+
# Save and push the trained model and tokenizer
|
| 125 |
+
if push_to_hub:
|
| 126 |
+
# Push the main model to the hub
|
| 127 |
+
trainer.push_to_hub(commit_message="Fine-tuned model")
|
| 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 GraLoRA 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("--gralora_r", type=int, default=8, help="LoRA rank")
|
| 154 |
+
parser.add_argument("--gralora_alpha", type=int, default=16, help="LoRA alpha")
|
| 155 |
+
parser.add_argument("--gralora_dropout", type=float, default=0.05, help="LoRA dropout rate")
|
| 156 |
+
parser.add_argument(
|
| 157 |
+
"--gralora_target_modules", type=str, default=None, help="Comma-separated list of target modules for LoRA"
|
| 158 |
+
)
|
| 159 |
+
parser.add_argument("--gralora_k", type=int, default=2, help="GraLoRA k")
|
| 160 |
+
parser.add_argument("--hybrid_r", type=int, default=0, help="Hybrid rank")
|
| 161 |
+
parser.add_argument(
|
| 162 |
+
"--hub_model_id",
|
| 163 |
+
type=str,
|
| 164 |
+
default="path/to/repo",
|
| 165 |
+
help="Repository name to push the model on the Hugging Face Hub",
|
| 166 |
+
)
|
| 167 |
+
parser.add_argument("--push_to_hub", action="store_true", help="Whether to push the model to Hugging Face Hub")
|
| 168 |
+
args = parser.parse_args()
|
| 169 |
+
train_model(
|
| 170 |
+
base_model=args.base_model,
|
| 171 |
+
data_path=args.data_path,
|
| 172 |
+
output_dir=args.output_dir,
|
| 173 |
+
batch_size=args.batch_size,
|
| 174 |
+
num_epochs=args.num_epochs,
|
| 175 |
+
learning_rate=args.learning_rate,
|
| 176 |
+
cutoff_len=args.cutoff_len,
|
| 177 |
+
val_set_size=args.val_set_size,
|
| 178 |
+
eval_step=args.eval_step,
|
| 179 |
+
save_step=args.save_step,
|
| 180 |
+
device=args.device,
|
| 181 |
+
gralora_r=args.gralora_r,
|
| 182 |
+
gralora_alpha=args.gralora_alpha,
|
| 183 |
+
gralora_dropout=args.gralora_dropout,
|
| 184 |
+
gralora_target_modules=args.gralora_target_modules,
|
| 185 |
+
gralora_k=args.gralora_k,
|
| 186 |
+
hybrid_r=args.hybrid_r,
|
| 187 |
+
hub_model_id=args.hub_model_id,
|
| 188 |
+
push_to_hub=args.push_to_hub,
|
| 189 |
+
)
|
tasks/tasksmith-ecb1931929df/tests/source/examples/hra_dreambooth/README.md
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# DreamBooth fine-tuning with HRA
|
| 18 |
+
|
| 19 |
+
This guide demonstrates how to use Householder reflection adaptation (HRA) method, to fine-tune Dreambooth with `stabilityai/stable-diffusion-2-1` model.
|
| 20 |
+
|
| 21 |
+
HRA provides a new perspective connecting LoRA to OFT and achieves encouraging performance in various downstream tasks.
|
| 22 |
+
HRA adapts a pre-trained model by multiplying each frozen weight matrix with a chain of r learnable Householder reflections (HRs).
|
| 23 |
+
HRA can be interpreted as either an OFT adapter or an adaptive LoRA.
|
| 24 |
+
Consequently, it harnesses the advantages of both strategies, reducing parameters and computation costs while penalizing the loss of pre-training knowledge.
|
| 25 |
+
For further details on HRA, please consult the [original HRA paper](https://huggingface.co/papers/2405.17484).
|
| 26 |
+
|
| 27 |
+
In this guide we provide a Dreambooth fine-tuning script that is available in [PEFT's GitHub repo examples](https://github.com/huggingface/peft/tree/main/examples/hra_dreambooth). This implementation is adapted from [peft's boft_dreambooth](https://github.com/huggingface/peft/tree/main/examples/boft_dreambooth).
|
| 28 |
+
|
| 29 |
+
You can try it out and fine-tune on your custom images.
|
| 30 |
+
|
| 31 |
+
## Set up your environment
|
| 32 |
+
|
| 33 |
+
Start by cloning the PEFT repository:
|
| 34 |
+
|
| 35 |
+
```bash
|
| 36 |
+
git clone --recursive https://github.com/huggingface/peft
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
Navigate to the directory containing the training scripts for fine-tuning Dreambooth with HRA:
|
| 40 |
+
|
| 41 |
+
```bash
|
| 42 |
+
cd peft/examples/hra_dreambooth
|
| 43 |
+
```
|
| 44 |
+
|
| 45 |
+
Set up your environment: install PEFT, and all the required libraries. At the time of writing this guide we recommend installing PEFT from source. The following environment setup should work on A100 and H100:
|
| 46 |
+
|
| 47 |
+
```bash
|
| 48 |
+
conda create --name peft python=3.10
|
| 49 |
+
conda activate peft
|
| 50 |
+
conda install pytorch==2.1.2 torchvision==0.16.2 torchaudio==2.1.2 pytorch-cuda=11.8 -c pytorch -c nvidia
|
| 51 |
+
conda install xformers -c xformers
|
| 52 |
+
pip install -r requirements.txt
|
| 53 |
+
pip install git+https://github.com/huggingface/peft
|
| 54 |
+
```
|
| 55 |
+
|
| 56 |
+
## Download the data
|
| 57 |
+
|
| 58 |
+
[dreambooth](https://github.com/google/dreambooth) dataset should have been automatically cloned in the following structure when running the training script.
|
| 59 |
+
|
| 60 |
+
```
|
| 61 |
+
hra_dreambooth
|
| 62 |
+
├── data
|
| 63 |
+
│ └── dreambooth
|
| 64 |
+
│ └── dataset
|
| 65 |
+
│ ├── backpack
|
| 66 |
+
│ └── backpack_dog
|
| 67 |
+
│ ...
|
| 68 |
+
```
|
| 69 |
+
|
| 70 |
+
You can also put your custom images into `hra_dreambooth/data/dreambooth/dataset`.
|
| 71 |
+
|
| 72 |
+
## Fine-tune Dreambooth with HRA
|
| 73 |
+
|
| 74 |
+
```bash
|
| 75 |
+
class_idx=0
|
| 76 |
+
bash ./train_dreambooth.sh $class_idx
|
| 77 |
+
```
|
| 78 |
+
|
| 79 |
+
where the `$class_idx` corresponds to different subjects ranging from 0 to 29.
|
| 80 |
+
|
| 81 |
+
Launch the training script with `accelerate` and pass hyperparameters, as well as LoRa-specific arguments to it such as:
|
| 82 |
+
|
| 83 |
+
- `use_hra`: Enables HRA in the training script.
|
| 84 |
+
- `hra_r`: the number of HRs (i.e., r) across different layers, expressed in `int`.
|
| 85 |
+
As r increases, the number of trainable parameters increases, which generally leads to improved performance.
|
| 86 |
+
However, this also results in higher memory consumption and longer computation times.
|
| 87 |
+
Therefore, r is usually set to 8.
|
| 88 |
+
**Note**, please set r to an even number to avoid potential issues during initialization.
|
| 89 |
+
- `hra_apply_GS`: Applies Gram-Schmidt orthogonalization. Default is `false`.
|
| 90 |
+
- `hra_bias`: specify if the `bias` parameters should be trained. Can be `none`, `all` or `hra_only`.
|
| 91 |
+
|
| 92 |
+
If you are running this script on Windows, you may need to set the `--num_dataloader_workers` to 0.
|
| 93 |
+
|
| 94 |
+
To learn more about DreamBooth fine-tuning with prior-preserving loss, check out the [Diffusers documentation](https://huggingface.co/docs/diffusers/training/dreambooth#finetuning-with-priorpreserving-loss).
|
| 95 |
+
|
| 96 |
+
## Generate images with the fine-tuned model
|
| 97 |
+
|
| 98 |
+
To generate images with the fine-tuned model, simply run the jupyter notebook `dreambooth_inference.ipynb` for visualization with `jupyter notebook` under `./examples/hra_dreambooth`.
|
tasks/tasksmith-ecb1931929df/tests/source/examples/hra_dreambooth/a_purple_qwe_backpack.png
ADDED
|
Git LFS Details
|
tasks/tasksmith-ecb1931929df/tests/source/examples/hra_dreambooth/dreambooth_inference.ipynb
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tasks/tasksmith-ecb1931929df/tests/source/examples/hra_dreambooth/requirements.txt
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
transformers==4.55.0
|
| 2 |
+
accelerate==1.9.0
|
| 3 |
+
evaluate
|
| 4 |
+
tqdm
|
| 5 |
+
datasets==4.0.0
|
| 6 |
+
diffusers==0.34.0
|
| 7 |
+
Pillow
|
| 8 |
+
huggingface_hub
|
| 9 |
+
safetensors
|
| 10 |
+
ipykernel
|
| 11 |
+
ipywidgets
|
| 12 |
+
wandb==0.21.0
|
tasks/tasksmith-ecb1931929df/tests/source/examples/hra_dreambooth/train_dreambooth.py
ADDED
|
@@ -0,0 +1,621 @@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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# Copyright 2024-present the HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
# The implementation is based on "Bridging The Gap between Low-rank and Orthogonal
|
| 17 |
+
# Adaptation via Householder Reflection Adaptation" (https://huggingface.co/papers/2405.17484).
|
| 18 |
+
|
| 19 |
+
import hashlib
|
| 20 |
+
import itertools
|
| 21 |
+
import logging
|
| 22 |
+
import math
|
| 23 |
+
import os
|
| 24 |
+
from contextlib import nullcontext
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
|
| 27 |
+
import datasets
|
| 28 |
+
import diffusers
|
| 29 |
+
import numpy as np
|
| 30 |
+
import torch
|
| 31 |
+
import torch.nn.functional as F
|
| 32 |
+
import torch.utils.checkpoint
|
| 33 |
+
import transformers
|
| 34 |
+
from accelerate import Accelerator
|
| 35 |
+
from accelerate.logging import get_logger
|
| 36 |
+
from accelerate.utils import ProjectConfiguration, set_seed
|
| 37 |
+
from diffusers import (
|
| 38 |
+
AutoencoderKL,
|
| 39 |
+
DDIMScheduler,
|
| 40 |
+
DiffusionPipeline,
|
| 41 |
+
DPMSolverMultistepScheduler,
|
| 42 |
+
UNet2DConditionModel,
|
| 43 |
+
)
|
| 44 |
+
from diffusers.optimization import get_scheduler
|
| 45 |
+
from diffusers.utils import check_min_version
|
| 46 |
+
from diffusers.utils.import_utils import is_xformers_available
|
| 47 |
+
from huggingface_hub import Repository
|
| 48 |
+
from tqdm.auto import tqdm
|
| 49 |
+
from transformers import AutoTokenizer
|
| 50 |
+
from utils.args_loader import (
|
| 51 |
+
get_full_repo_name,
|
| 52 |
+
import_model_class_from_model_name_or_path,
|
| 53 |
+
parse_args,
|
| 54 |
+
)
|
| 55 |
+
from utils.dataset import DreamBoothDataset, PromptDataset, collate_fn
|
| 56 |
+
from utils.tracemalloc import TorchTracemalloc, b2mb
|
| 57 |
+
|
| 58 |
+
from peft import HRAConfig, get_peft_model
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# Will error if the minimal version of diffusers is not installed. Remove at your own risks.
|
| 62 |
+
check_min_version("0.16.0.dev0")
|
| 63 |
+
|
| 64 |
+
logger = get_logger(__name__)
|
| 65 |
+
|
| 66 |
+
UNET_TARGET_MODULES = ["to_q", "to_v", "to_k", "query", "value", "key", "to_out.0", "add_k_proj", "add_v_proj"]
|
| 67 |
+
TEXT_ENCODER_TARGET_MODULES = ["q_proj", "v_proj"]
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def save_adaptor(accelerator, step, unet, text_encoder, args):
|
| 71 |
+
unwarpped_unet = accelerator.unwrap_model(unet)
|
| 72 |
+
unwarpped_unet.save_pretrained(
|
| 73 |
+
os.path.join(args.output_dir, f"unet/{step}"), state_dict=accelerator.get_state_dict(unet)
|
| 74 |
+
)
|
| 75 |
+
if args.train_text_encoder:
|
| 76 |
+
unwarpped_text_encoder = accelerator.unwrap_model(text_encoder)
|
| 77 |
+
unwarpped_text_encoder.save_pretrained(
|
| 78 |
+
os.path.join(args.output_dir, f"text_encoder/{step}"),
|
| 79 |
+
state_dict=accelerator.get_state_dict(text_encoder),
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def main(args):
|
| 84 |
+
validation_prompts = list(filter(None, args.validation_prompt[0].split(".")))
|
| 85 |
+
|
| 86 |
+
logging_dir = Path(args.output_dir, args.logging_dir)
|
| 87 |
+
accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
|
| 88 |
+
|
| 89 |
+
accelerator = Accelerator(
|
| 90 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
| 91 |
+
mixed_precision=args.mixed_precision,
|
| 92 |
+
log_with=args.report_to if args.report_to != "none" else None,
|
| 93 |
+
project_dir=accelerator_project_config,
|
| 94 |
+
)
|
| 95 |
+
if args.report_to == "wandb":
|
| 96 |
+
import wandb
|
| 97 |
+
|
| 98 |
+
args.wandb_project_name = args.project_name
|
| 99 |
+
args.wandb_run_name = args.run_name
|
| 100 |
+
wandb_init = {
|
| 101 |
+
"wandb": {
|
| 102 |
+
"name": args.wandb_run_name,
|
| 103 |
+
"mode": "online",
|
| 104 |
+
}
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
# Currently, it's not possible to do gradient accumulation when training two models with accelerate.accumulate
|
| 108 |
+
# This will be enabled soon in accelerate. For now, we don't allow gradient accumulation when training two models.
|
| 109 |
+
# TODO (patil-suraj): Remove this check when gradient accumulation with two models is enabled in accelerate.
|
| 110 |
+
if args.train_text_encoder and args.gradient_accumulation_steps > 1 and accelerator.num_processes > 1:
|
| 111 |
+
raise ValueError(
|
| 112 |
+
"Gradient accumulation is not supported when training the text encoder in distributed training. "
|
| 113 |
+
"Please set gradient_accumulation_steps to 1. This feature will be supported in the future."
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
# Make one log on every process with the configuration for debugging.
|
| 117 |
+
logging.basicConfig(
|
| 118 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
| 119 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
| 120 |
+
level=logging.INFO,
|
| 121 |
+
)
|
| 122 |
+
logger.info(accelerator.state, main_process_only=False)
|
| 123 |
+
if accelerator.is_local_main_process:
|
| 124 |
+
datasets.utils.logging.set_verbosity_warning()
|
| 125 |
+
transformers.utils.logging.set_verbosity_warning()
|
| 126 |
+
diffusers.utils.logging.set_verbosity_info()
|
| 127 |
+
else:
|
| 128 |
+
datasets.utils.logging.set_verbosity_error()
|
| 129 |
+
transformers.utils.logging.set_verbosity_error()
|
| 130 |
+
diffusers.utils.logging.set_verbosity_error()
|
| 131 |
+
|
| 132 |
+
# If passed along, set the training seed now.
|
| 133 |
+
global_seed = hash(args.run_name) % (2**32)
|
| 134 |
+
set_seed(global_seed)
|
| 135 |
+
|
| 136 |
+
# Generate class images if prior preservation is enabled.
|
| 137 |
+
if args.with_prior_preservation:
|
| 138 |
+
class_images_dir = Path(args.class_data_dir)
|
| 139 |
+
if not class_images_dir.exists():
|
| 140 |
+
class_images_dir.mkdir(parents=True)
|
| 141 |
+
cur_class_images = len(list(class_images_dir.iterdir()))
|
| 142 |
+
|
| 143 |
+
if cur_class_images < args.num_class_images:
|
| 144 |
+
dtype = torch.float16 if accelerator.device.type in ["cuda", "xpu"] else torch.float32
|
| 145 |
+
if args.prior_generation_precision == "fp32":
|
| 146 |
+
dtype = torch.float32
|
| 147 |
+
elif args.prior_generation_precision == "fp16":
|
| 148 |
+
dtype = torch.float16
|
| 149 |
+
elif args.prior_generation_precision == "bf16":
|
| 150 |
+
dtype = torch.bfloat16
|
| 151 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
| 152 |
+
args.pretrained_model_name_or_path,
|
| 153 |
+
dtype=dtype,
|
| 154 |
+
safety_checker=None,
|
| 155 |
+
revision=args.revision,
|
| 156 |
+
)
|
| 157 |
+
pipeline.set_progress_bar_config(disable=True)
|
| 158 |
+
|
| 159 |
+
num_new_images = args.num_class_images - cur_class_images
|
| 160 |
+
logger.info(f"Number of class images to sample: {num_new_images}.")
|
| 161 |
+
|
| 162 |
+
sample_dataset = PromptDataset(args.class_prompt, num_new_images)
|
| 163 |
+
sample_dataloader = torch.utils.data.DataLoader(sample_dataset, batch_size=args.sample_batch_size)
|
| 164 |
+
|
| 165 |
+
sample_dataloader = accelerator.prepare(sample_dataloader)
|
| 166 |
+
pipeline.to(accelerator.device)
|
| 167 |
+
|
| 168 |
+
for example in tqdm(
|
| 169 |
+
sample_dataloader, desc="Generating class images", disable=not accelerator.is_local_main_process
|
| 170 |
+
):
|
| 171 |
+
images = pipeline(example["prompt"]).images
|
| 172 |
+
|
| 173 |
+
for i, image in enumerate(images):
|
| 174 |
+
hash_image = hashlib.sha1(image.tobytes()).hexdigest()
|
| 175 |
+
image_filename = class_images_dir / f"{example['index'][i] + cur_class_images}-{hash_image}.jpg"
|
| 176 |
+
image.save(image_filename)
|
| 177 |
+
|
| 178 |
+
del pipeline
|
| 179 |
+
if torch.cuda.is_available():
|
| 180 |
+
torch.cuda.empty_cache()
|
| 181 |
+
elif torch.xpu.is_available():
|
| 182 |
+
torch.xpu.empty_cache()
|
| 183 |
+
|
| 184 |
+
# Handle the repository creation
|
| 185 |
+
if accelerator.is_main_process:
|
| 186 |
+
if args.push_to_hub:
|
| 187 |
+
if args.hub_model_id is None:
|
| 188 |
+
repo_name = get_full_repo_name(Path(args.output_dir).name, token=args.hub_token)
|
| 189 |
+
else:
|
| 190 |
+
repo_name = args.hub_model_id
|
| 191 |
+
repo = Repository(args.output_dir, clone_from=repo_name) # noqa: F841
|
| 192 |
+
|
| 193 |
+
with open(os.path.join(args.output_dir, ".gitignore"), "w+") as gitignore:
|
| 194 |
+
if "step_*" not in gitignore:
|
| 195 |
+
gitignore.write("step_*\n")
|
| 196 |
+
if "epoch_*" not in gitignore:
|
| 197 |
+
gitignore.write("epoch_*\n")
|
| 198 |
+
elif args.output_dir is not None:
|
| 199 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 200 |
+
|
| 201 |
+
# Load the tokenizer
|
| 202 |
+
if args.tokenizer_name:
|
| 203 |
+
tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name, revision=args.revision, use_fast=False)
|
| 204 |
+
elif args.pretrained_model_name_or_path:
|
| 205 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 206 |
+
args.pretrained_model_name_or_path,
|
| 207 |
+
subfolder="tokenizer",
|
| 208 |
+
revision=args.revision,
|
| 209 |
+
use_fast=False,
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
# import correct text encoder class
|
| 213 |
+
text_encoder_cls = import_model_class_from_model_name_or_path(args.pretrained_model_name_or_path, args.revision)
|
| 214 |
+
|
| 215 |
+
# Load scheduler and models
|
| 216 |
+
noise_scheduler = DDIMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
|
| 217 |
+
|
| 218 |
+
text_encoder = text_encoder_cls.from_pretrained(
|
| 219 |
+
args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision
|
| 220 |
+
)
|
| 221 |
+
vae = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae", revision=args.revision)
|
| 222 |
+
unet = UNet2DConditionModel.from_pretrained(
|
| 223 |
+
args.pretrained_model_name_or_path, subfolder="unet", revision=args.revision
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
if args.use_hra:
|
| 227 |
+
config = HRAConfig(
|
| 228 |
+
r=args.hra_r,
|
| 229 |
+
apply_GS=args.hra_apply_GS,
|
| 230 |
+
target_modules=UNET_TARGET_MODULES,
|
| 231 |
+
bias=args.hra_bias,
|
| 232 |
+
)
|
| 233 |
+
unet = get_peft_model(unet, config, adapter_name=args.run_name)
|
| 234 |
+
unet.print_trainable_parameters()
|
| 235 |
+
|
| 236 |
+
vae.requires_grad_(False)
|
| 237 |
+
unet.train()
|
| 238 |
+
|
| 239 |
+
if args.train_text_encoder and args.use_hra:
|
| 240 |
+
config = HRAConfig(
|
| 241 |
+
r=args.hra_r,
|
| 242 |
+
apply_GS=args.hra_apply_GS,
|
| 243 |
+
target_modules=UNET_TARGET_MODULES,
|
| 244 |
+
bias=args.hra_bias,
|
| 245 |
+
)
|
| 246 |
+
text_encoder = get_peft_model(text_encoder, config, adapter_name=args.run_name)
|
| 247 |
+
text_encoder.print_trainable_parameters()
|
| 248 |
+
text_encoder.train()
|
| 249 |
+
else:
|
| 250 |
+
text_encoder.requires_grad_(False)
|
| 251 |
+
|
| 252 |
+
# For mixed precision training we cast the text_encoder and vae weights to half-precision
|
| 253 |
+
# as these models are only used for inference, keeping weights in full precision is not required.
|
| 254 |
+
weight_dtype = torch.float32
|
| 255 |
+
if accelerator.mixed_precision == "fp16":
|
| 256 |
+
weight_dtype = torch.float16
|
| 257 |
+
elif accelerator.mixed_precision == "bf16":
|
| 258 |
+
weight_dtype = torch.bfloat16
|
| 259 |
+
|
| 260 |
+
# Move unet, vae and text_encoder to device and cast to weight_dtype
|
| 261 |
+
unet.to(accelerator.device, dtype=weight_dtype)
|
| 262 |
+
vae.to(accelerator.device, dtype=weight_dtype)
|
| 263 |
+
text_encoder.to(accelerator.device, dtype=weight_dtype)
|
| 264 |
+
|
| 265 |
+
if args.enable_xformers_memory_efficient_attention:
|
| 266 |
+
if accelerator.device.type == "xpu":
|
| 267 |
+
logger.warning("XPU hasn't support xformers yet, ignore it.")
|
| 268 |
+
elif is_xformers_available():
|
| 269 |
+
unet.enable_xformers_memory_efficient_attention()
|
| 270 |
+
else:
|
| 271 |
+
raise ValueError("xformers is not available. Make sure it is installed correctly")
|
| 272 |
+
|
| 273 |
+
if args.gradient_checkpointing:
|
| 274 |
+
unet.enable_gradient_checkpointing()
|
| 275 |
+
# below fails when using hra so commenting it out
|
| 276 |
+
if args.train_text_encoder and not args.use_hra:
|
| 277 |
+
text_encoder.gradient_checkpointing_enable()
|
| 278 |
+
|
| 279 |
+
# Enable TF32 for faster training on Ampere GPUs,
|
| 280 |
+
# cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
|
| 281 |
+
if args.allow_tf32:
|
| 282 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 283 |
+
|
| 284 |
+
if args.scale_lr:
|
| 285 |
+
args.learning_rate = (
|
| 286 |
+
args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
# Use 8-bit Adam for lower memory usage or to fine-tune the model in 16GB GPUs
|
| 290 |
+
if args.use_8bit_adam:
|
| 291 |
+
try:
|
| 292 |
+
import bitsandbytes as bnb
|
| 293 |
+
except ImportError:
|
| 294 |
+
raise ImportError(
|
| 295 |
+
"To use 8-bit Adam, please install the bitsandbytes library: `pip install bitsandbytes`."
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
optimizer_class = bnb.optim.AdamW8bit
|
| 299 |
+
else:
|
| 300 |
+
optimizer_class = torch.optim.AdamW
|
| 301 |
+
|
| 302 |
+
# Optimizer creation
|
| 303 |
+
params_to_optimize = [param for param in unet.parameters() if param.requires_grad]
|
| 304 |
+
|
| 305 |
+
if args.train_text_encoder:
|
| 306 |
+
params_to_optimize += [param for param in text_encoder.parameters() if param.requires_grad]
|
| 307 |
+
|
| 308 |
+
optimizer = optimizer_class(
|
| 309 |
+
params_to_optimize,
|
| 310 |
+
lr=args.learning_rate,
|
| 311 |
+
betas=(args.adam_beta1, args.adam_beta2),
|
| 312 |
+
weight_decay=args.adam_weight_decay,
|
| 313 |
+
eps=args.adam_epsilon,
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
# Download the official dreambooth dataset from the official repository: https://github.com/google/dreambooth.git
|
| 317 |
+
data_path = os.path.join(os.getcwd(), "data", "dreambooth")
|
| 318 |
+
if not os.path.exists(data_path):
|
| 319 |
+
os.makedirs(os.path.join(os.getcwd(), "data"), exist_ok=True)
|
| 320 |
+
os.system(f"git clone https://github.com/google/dreambooth.git '{data_path}'")
|
| 321 |
+
|
| 322 |
+
# Dataset and DataLoaders creation:
|
| 323 |
+
train_dataset = DreamBoothDataset(
|
| 324 |
+
instance_data_root=args.instance_data_dir,
|
| 325 |
+
instance_prompt=args.instance_prompt,
|
| 326 |
+
class_data_root=args.class_data_dir if args.with_prior_preservation else None,
|
| 327 |
+
class_prompt=args.class_prompt,
|
| 328 |
+
tokenizer=tokenizer,
|
| 329 |
+
size=args.resolution,
|
| 330 |
+
center_crop=args.center_crop,
|
| 331 |
+
)
|
| 332 |
+
|
| 333 |
+
train_dataloader = torch.utils.data.DataLoader(
|
| 334 |
+
train_dataset,
|
| 335 |
+
batch_size=args.train_batch_size,
|
| 336 |
+
shuffle=True,
|
| 337 |
+
collate_fn=lambda examples: collate_fn(examples, args.with_prior_preservation),
|
| 338 |
+
num_workers=args.num_dataloader_workers,
|
| 339 |
+
)
|
| 340 |
+
|
| 341 |
+
# Scheduler and math around the number of training steps.
|
| 342 |
+
overrode_max_train_steps = False
|
| 343 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
| 344 |
+
if args.max_train_steps is None:
|
| 345 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 346 |
+
overrode_max_train_steps = True
|
| 347 |
+
|
| 348 |
+
lr_scheduler = get_scheduler(
|
| 349 |
+
args.lr_scheduler,
|
| 350 |
+
optimizer=optimizer,
|
| 351 |
+
num_warmup_steps=args.lr_warmup_steps * args.gradient_accumulation_steps,
|
| 352 |
+
num_training_steps=args.max_train_steps * args.gradient_accumulation_steps,
|
| 353 |
+
num_cycles=args.lr_num_cycles,
|
| 354 |
+
power=args.lr_power,
|
| 355 |
+
)
|
| 356 |
+
|
| 357 |
+
# Prepare everything with our `accelerator`.
|
| 358 |
+
if args.train_text_encoder:
|
| 359 |
+
unet, text_encoder, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
|
| 360 |
+
unet, text_encoder, optimizer, train_dataloader, lr_scheduler
|
| 361 |
+
)
|
| 362 |
+
else:
|
| 363 |
+
unet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
|
| 364 |
+
unet, optimizer, train_dataloader, lr_scheduler
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
# For mixed precision training we cast the text_encoder and vae weights to half-precision
|
| 368 |
+
# as these models are only used for inference, keeping weights in full precision is not required.
|
| 369 |
+
weight_dtype = torch.float32
|
| 370 |
+
if accelerator.mixed_precision == "fp16":
|
| 371 |
+
weight_dtype = torch.float16
|
| 372 |
+
elif accelerator.mixed_precision == "bf16":
|
| 373 |
+
weight_dtype = torch.bfloat16
|
| 374 |
+
|
| 375 |
+
# Move vae and text_encoder to device and cast to weight_dtype
|
| 376 |
+
vae.to(accelerator.device, dtype=weight_dtype)
|
| 377 |
+
if not args.train_text_encoder:
|
| 378 |
+
text_encoder.to(accelerator.device, dtype=weight_dtype)
|
| 379 |
+
|
| 380 |
+
# We need to recalculate our total training steps as the size of the training dataloader may have changed.
|
| 381 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
| 382 |
+
if overrode_max_train_steps:
|
| 383 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 384 |
+
# Afterwards we recalculate our number of training epochs
|
| 385 |
+
args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
|
| 386 |
+
|
| 387 |
+
# We need to initialize the trackers we use, and also store our configuration.
|
| 388 |
+
# The trackers initializes automatically on the main process.
|
| 389 |
+
if accelerator.is_main_process:
|
| 390 |
+
if args.report_to == "wandb":
|
| 391 |
+
accelerator.init_trackers(args.wandb_project_name, config=vars(args), init_kwargs=wandb_init)
|
| 392 |
+
else:
|
| 393 |
+
accelerator.init_trackers(args.project_name, config=vars(args))
|
| 394 |
+
|
| 395 |
+
# Train!
|
| 396 |
+
total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
|
| 397 |
+
|
| 398 |
+
logger.info("***** Running training *****")
|
| 399 |
+
logger.info(f" Num examples = {len(train_dataset)}")
|
| 400 |
+
logger.info(f" Num batches each epoch = {len(train_dataloader)}")
|
| 401 |
+
logger.info(f" Num Epochs = {args.num_train_epochs}")
|
| 402 |
+
logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
|
| 403 |
+
logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
|
| 404 |
+
logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
|
| 405 |
+
logger.info(f" Total optimization steps = {args.max_train_steps}")
|
| 406 |
+
global_step = 0
|
| 407 |
+
first_epoch = 0
|
| 408 |
+
|
| 409 |
+
# Potentially load in the weights and states from a previous save
|
| 410 |
+
if args.resume_from_checkpoint:
|
| 411 |
+
if args.resume_from_checkpoint != "latest":
|
| 412 |
+
path = os.path.basename(args.resume_from_checkpoint)
|
| 413 |
+
else:
|
| 414 |
+
# Get the most recent checkpoint
|
| 415 |
+
dirs = os.listdir(args.output_dir)
|
| 416 |
+
dirs = [d for d in dirs if d.startswith("checkpoint")]
|
| 417 |
+
dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
|
| 418 |
+
path = dirs[-1] if len(dirs) > 0 else None
|
| 419 |
+
accelerator.print(f"Resuming from checkpoint {path}")
|
| 420 |
+
accelerator.load_state(os.path.join(args.output_dir, path))
|
| 421 |
+
global_step = int(path.split("-")[1])
|
| 422 |
+
|
| 423 |
+
resume_global_step = global_step * args.gradient_accumulation_steps
|
| 424 |
+
first_epoch = resume_global_step // num_update_steps_per_epoch
|
| 425 |
+
resume_step = resume_global_step % num_update_steps_per_epoch
|
| 426 |
+
|
| 427 |
+
# Only show the progress bar once on each machine.
|
| 428 |
+
progress_bar = tqdm(range(global_step, args.max_train_steps), disable=not accelerator.is_local_main_process)
|
| 429 |
+
progress_bar.set_description("Steps")
|
| 430 |
+
|
| 431 |
+
if args.train_text_encoder:
|
| 432 |
+
text_encoder.train()
|
| 433 |
+
|
| 434 |
+
for epoch in range(first_epoch, args.num_train_epochs):
|
| 435 |
+
unet.train()
|
| 436 |
+
|
| 437 |
+
with TorchTracemalloc() if not args.no_tracemalloc else nullcontext() as tracemalloc:
|
| 438 |
+
for step, batch in enumerate(train_dataloader):
|
| 439 |
+
# Skip steps until we reach the resumed step
|
| 440 |
+
if args.resume_from_checkpoint and epoch == first_epoch and step < resume_step:
|
| 441 |
+
if step % args.gradient_accumulation_steps == 0:
|
| 442 |
+
progress_bar.update(1)
|
| 443 |
+
if args.report_to == "wandb":
|
| 444 |
+
accelerator.print(progress_bar)
|
| 445 |
+
continue
|
| 446 |
+
|
| 447 |
+
with accelerator.accumulate(unet):
|
| 448 |
+
# Convert images to latent space
|
| 449 |
+
latents = vae.encode(batch["pixel_values"].to(dtype=weight_dtype)).latent_dist.sample()
|
| 450 |
+
latents = latents * vae.config.scaling_factor
|
| 451 |
+
|
| 452 |
+
# Sample noise that we'll add to the latents
|
| 453 |
+
noise = torch.randn_like(latents)
|
| 454 |
+
bsz = latents.shape[0]
|
| 455 |
+
# Sample a random timestep for each image
|
| 456 |
+
timesteps = torch.randint(
|
| 457 |
+
0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device
|
| 458 |
+
)
|
| 459 |
+
timesteps = timesteps.long()
|
| 460 |
+
|
| 461 |
+
# Add noise to the latents according to the noise magnitude at each timestep
|
| 462 |
+
# (this is the forward diffusion process)
|
| 463 |
+
noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
|
| 464 |
+
|
| 465 |
+
# Get the text embedding for conditioning
|
| 466 |
+
encoder_hidden_states = text_encoder(batch["input_ids"])[0]
|
| 467 |
+
|
| 468 |
+
# Predict the noise residual
|
| 469 |
+
model_pred = unet(noisy_latents, timesteps, encoder_hidden_states).sample
|
| 470 |
+
|
| 471 |
+
# Get the target for loss depending on the prediction type
|
| 472 |
+
if noise_scheduler.config.prediction_type == "epsilon":
|
| 473 |
+
target = noise
|
| 474 |
+
elif noise_scheduler.config.prediction_type == "v_prediction":
|
| 475 |
+
target = noise_scheduler.get_velocity(latents, noise, timesteps)
|
| 476 |
+
else:
|
| 477 |
+
raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
|
| 478 |
+
|
| 479 |
+
if args.with_prior_preservation:
|
| 480 |
+
# Chunk the noise and model_pred into two parts and compute the loss on each part separately.
|
| 481 |
+
model_pred, model_pred_prior = torch.chunk(model_pred, 2, dim=0)
|
| 482 |
+
target, target_prior = torch.chunk(target, 2, dim=0)
|
| 483 |
+
|
| 484 |
+
# Compute instance loss
|
| 485 |
+
loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
|
| 486 |
+
|
| 487 |
+
# Compute prior loss
|
| 488 |
+
prior_loss = F.mse_loss(model_pred_prior.float(), target_prior.float(), reduction="mean")
|
| 489 |
+
|
| 490 |
+
# Add the prior loss to the instance loss.
|
| 491 |
+
loss = loss + args.prior_loss_weight * prior_loss
|
| 492 |
+
else:
|
| 493 |
+
loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
|
| 494 |
+
|
| 495 |
+
accelerator.backward(loss)
|
| 496 |
+
|
| 497 |
+
if accelerator.sync_gradients:
|
| 498 |
+
params_to_clip = (
|
| 499 |
+
itertools.chain(unet.parameters(), text_encoder.parameters())
|
| 500 |
+
if args.train_text_encoder
|
| 501 |
+
else unet.parameters()
|
| 502 |
+
)
|
| 503 |
+
accelerator.clip_grad_norm_(params_to_clip, args.max_grad_norm)
|
| 504 |
+
|
| 505 |
+
optimizer.step()
|
| 506 |
+
lr_scheduler.step()
|
| 507 |
+
optimizer.zero_grad()
|
| 508 |
+
|
| 509 |
+
# Checks if the accelerator has performed an optimization step behind the scenes
|
| 510 |
+
if accelerator.sync_gradients:
|
| 511 |
+
progress_bar.update(1)
|
| 512 |
+
if args.report_to == "wandb":
|
| 513 |
+
accelerator.print(progress_bar)
|
| 514 |
+
global_step += 1
|
| 515 |
+
|
| 516 |
+
if global_step % args.checkpointing_steps == 0 and global_step != 0:
|
| 517 |
+
if accelerator.is_main_process:
|
| 518 |
+
save_adaptor(accelerator, global_step, unet, text_encoder, args)
|
| 519 |
+
|
| 520 |
+
logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
|
| 521 |
+
progress_bar.set_postfix(**logs)
|
| 522 |
+
accelerator.log(logs, step=global_step)
|
| 523 |
+
|
| 524 |
+
if (
|
| 525 |
+
args.validation_prompt is not None
|
| 526 |
+
and (step + num_update_steps_per_epoch * epoch) % args.validation_steps == 0
|
| 527 |
+
and global_step > 10
|
| 528 |
+
):
|
| 529 |
+
unet.eval()
|
| 530 |
+
|
| 531 |
+
logger.info(
|
| 532 |
+
f"Running validation... \n Generating {len(validation_prompts)} images with prompt:"
|
| 533 |
+
f" {validation_prompts[0]}, ......"
|
| 534 |
+
)
|
| 535 |
+
# create pipeline
|
| 536 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
| 537 |
+
args.pretrained_model_name_or_path,
|
| 538 |
+
safety_checker=None,
|
| 539 |
+
revision=args.revision,
|
| 540 |
+
)
|
| 541 |
+
# set `keep_fp32_wrapper` to True because we do not want to remove
|
| 542 |
+
# mixed precision hooks while we are still training
|
| 543 |
+
pipeline.unet = accelerator.unwrap_model(unet, keep_fp32_wrapper=True)
|
| 544 |
+
pipeline.text_encoder = accelerator.unwrap_model(text_encoder, keep_fp32_wrapper=True)
|
| 545 |
+
pipeline.scheduler = DPMSolverMultistepScheduler.from_config(pipeline.scheduler.config)
|
| 546 |
+
pipeline = pipeline.to(accelerator.device)
|
| 547 |
+
pipeline.set_progress_bar_config(disable=True)
|
| 548 |
+
|
| 549 |
+
# run inference
|
| 550 |
+
if args.seed is not None:
|
| 551 |
+
generator = torch.Generator(device=accelerator.device).manual_seed(args.seed)
|
| 552 |
+
else:
|
| 553 |
+
generator = None
|
| 554 |
+
|
| 555 |
+
images = []
|
| 556 |
+
val_img_dir = os.path.join(
|
| 557 |
+
args.output_dir,
|
| 558 |
+
f"validation/{global_step}",
|
| 559 |
+
args.run_name,
|
| 560 |
+
)
|
| 561 |
+
os.makedirs(val_img_dir, exist_ok=True)
|
| 562 |
+
|
| 563 |
+
for val_promot in validation_prompts:
|
| 564 |
+
image = pipeline(val_promot, num_inference_steps=50, generator=generator).images[0]
|
| 565 |
+
image.save(os.path.join(val_img_dir, f"{'_'.join(val_promot.split(' '))}.png"[1:]))
|
| 566 |
+
images.append(image)
|
| 567 |
+
|
| 568 |
+
for tracker in accelerator.trackers:
|
| 569 |
+
if tracker.name == "tensorboard":
|
| 570 |
+
np_images = np.stack([np.asarray(img) for img in images])
|
| 571 |
+
tracker.writer.add_images("validation", np_images, epoch, dataformats="NHWC")
|
| 572 |
+
if tracker.name == "wandb":
|
| 573 |
+
import wandb
|
| 574 |
+
|
| 575 |
+
tracker.log(
|
| 576 |
+
{
|
| 577 |
+
"validation": [
|
| 578 |
+
wandb.Image(image, caption=f"{i}: {validation_prompts[i]}")
|
| 579 |
+
for i, image in enumerate(images)
|
| 580 |
+
]
|
| 581 |
+
}
|
| 582 |
+
)
|
| 583 |
+
|
| 584 |
+
del pipeline
|
| 585 |
+
if torch.cuda.is_available():
|
| 586 |
+
torch.cuda.empty_cache()
|
| 587 |
+
elif torch.xpu.is_available():
|
| 588 |
+
torch.xpu.empty_cache()
|
| 589 |
+
if global_step >= args.max_train_steps:
|
| 590 |
+
break
|
| 591 |
+
|
| 592 |
+
# Printing the device memory usage details such as allocated memory, peak memory, and total memory usage
|
| 593 |
+
if not args.no_tracemalloc:
|
| 594 |
+
accelerator.print(
|
| 595 |
+
f"{accelerator.device.type.upper()} Memory before entering the train : {b2mb(tracemalloc.begin)}"
|
| 596 |
+
)
|
| 597 |
+
accelerator.print(
|
| 598 |
+
f"{accelerator.device.type.upper()} Memory consumed at the end of the train (end-begin): {tracemalloc.used}"
|
| 599 |
+
)
|
| 600 |
+
accelerator.print(
|
| 601 |
+
f"{accelerator.device.type.upper()} Peak Memory consumed during the train (max-begin): {tracemalloc.peaked}"
|
| 602 |
+
)
|
| 603 |
+
accelerator.print(
|
| 604 |
+
f"{accelerator.device.type.upper()} Total Peak Memory consumed during the train (max): {tracemalloc.peaked + b2mb(tracemalloc.begin)}"
|
| 605 |
+
)
|
| 606 |
+
|
| 607 |
+
accelerator.print(f"CPU Memory before entering the train : {b2mb(tracemalloc.cpu_begin)}")
|
| 608 |
+
accelerator.print(f"CPU Memory consumed at the end of the train (end-begin): {tracemalloc.cpu_used}")
|
| 609 |
+
accelerator.print(f"CPU Peak Memory consumed during the train (max-begin): {tracemalloc.cpu_peaked}")
|
| 610 |
+
accelerator.print(
|
| 611 |
+
f"CPU Total Peak Memory consumed during the train (max): {tracemalloc.cpu_peaked + b2mb(tracemalloc.cpu_begin)}"
|
| 612 |
+
)
|
| 613 |
+
|
| 614 |
+
if args.push_to_hub:
|
| 615 |
+
repo.push_to_hub(commit_message="End of training", blocking=False, auto_lfs_prune=True)
|
| 616 |
+
accelerator.end_training()
|
| 617 |
+
|
| 618 |
+
|
| 619 |
+
if __name__ == "__main__":
|
| 620 |
+
args = parse_args()
|
| 621 |
+
main(args)
|
tasks/tasksmith-ecb1931929df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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
CLASS_IDX=$1
|
| 3 |
+
|
| 4 |
+
# Define the UNIQUE_TOKEN, CLASS_TOKENs, and SUBJECT_NAMES
|
| 5 |
+
UNIQUE_TOKEN="qwe"
|
| 6 |
+
|
| 7 |
+
SUBJECT_NAMES=(
|
| 8 |
+
"backpack" "backpack_dog" "bear_plushie" "berry_bowl" "can"
|
| 9 |
+
"candle" "cat" "cat2" "clock" "colorful_sneaker"
|
| 10 |
+
"dog" "dog2" "dog3" "dog5" "dog6"
|
| 11 |
+
"dog7" "dog8" "duck_toy" "fancy_boot" "grey_sloth_plushie"
|
| 12 |
+
"monster_toy" "pink_sunglasses" "poop_emoji" "rc_car" "red_cartoon"
|
| 13 |
+
"robot_toy" "shiny_sneaker" "teapot" "vase" "wolf_plushie"
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
CLASS_TOKENs=(
|
| 17 |
+
"backpack" "backpack" "stuffed animal" "bowl" "can"
|
| 18 |
+
"candle" "cat" "cat" "clock" "sneaker"
|
| 19 |
+
"dog" "dog" "dog" "dog" "dog"
|
| 20 |
+
"dog" "dog" "toy" "boot" "stuffed animal"
|
| 21 |
+
"toy" "glasses" "toy" "toy" "cartoon"
|
| 22 |
+
"toy" "sneaker" "teapot" "vase" "stuffed animal"
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
CLASS_TOKEN=${CLASS_TOKENs[$CLASS_IDX]}
|
| 26 |
+
SELECTED_SUBJECT=${SUBJECT_NAMES[$CLASS_IDX]}
|
| 27 |
+
|
| 28 |
+
if [[ $CLASS_IDX =~ ^(0|1|2|3|4|5|8|9|17|18|19|20|21|22|23|24|25|26|27|28|29)$ ]]; then
|
| 29 |
+
PROMPT_LIST=(
|
| 30 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} in the jungle."
|
| 31 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} in the snow."
|
| 32 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} on the beach."
|
| 33 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} on a cobblestone street."
|
| 34 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} on top of pink fabric."
|
| 35 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} on top of a wooden floor."
|
| 36 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} with a city in the background."
|
| 37 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} with a mountain in the background."
|
| 38 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} with a blue house in the background."
|
| 39 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} on top of a purple rug in a forest."
|
| 40 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} with a wheat field in the background."
|
| 41 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} with a tree and autumn leaves in the background."
|
| 42 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} with the Eiffel Tower in the background."
|
| 43 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} floating on top of water."
|
| 44 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} floating in an ocean of milk."
|
| 45 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} on top of green grass with sunflowers around it."
|
| 46 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} on top of a mirror."
|
| 47 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} on top of the sidewalk in a crowded street."
|
| 48 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} on top of a dirt road."
|
| 49 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} on top of a white rug."
|
| 50 |
+
"a red ${UNIQUE_TOKEN} ${CLASS_TOKEN}."
|
| 51 |
+
"a purple ${UNIQUE_TOKEN} ${CLASS_TOKEN}."
|
| 52 |
+
"a shiny ${UNIQUE_TOKEN} ${CLASS_TOKEN}."
|
| 53 |
+
"a wet ${UNIQUE_TOKEN} ${CLASS_TOKEN}."
|
| 54 |
+
"a cube shaped ${UNIQUE_TOKEN} ${CLASS_TOKEN}."
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
prompt_test_list=(
|
| 58 |
+
"a ${CLASS_TOKEN} in the jungle"
|
| 59 |
+
"a ${CLASS_TOKEN} in the snow"
|
| 60 |
+
"a ${CLASS_TOKEN} on the beach"
|
| 61 |
+
"a ${CLASS_TOKEN} on a cobblestone street"
|
| 62 |
+
"a ${CLASS_TOKEN} on top of pink fabric"
|
| 63 |
+
"a ${CLASS_TOKEN} on top of a wooden floor"
|
| 64 |
+
"a ${CLASS_TOKEN} with a city in the background"
|
| 65 |
+
"a ${CLASS_TOKEN} with a mountain in the background"
|
| 66 |
+
"a ${CLASS_TOKEN} with a blue house in the background"
|
| 67 |
+
"a ${CLASS_TOKEN} on top of a purple rug in a forest"
|
| 68 |
+
"a ${CLASS_TOKEN} with a wheat field in the background"
|
| 69 |
+
"a ${CLASS_TOKEN} with a tree and autumn leaves in the background"
|
| 70 |
+
"a ${CLASS_TOKEN} with the Eiffel Tower in the background"
|
| 71 |
+
"a ${CLASS_TOKEN} floating on top of water"
|
| 72 |
+
"a ${CLASS_TOKEN} floating in an ocean of milk"
|
| 73 |
+
"a ${CLASS_TOKEN} on top of green grass with sunflowers around it"
|
| 74 |
+
"a ${CLASS_TOKEN} on top of a mirror"
|
| 75 |
+
"a ${CLASS_TOKEN} on top of the sidewalk in a crowded street"
|
| 76 |
+
"a ${CLASS_TOKEN} on top of a dirt road"
|
| 77 |
+
"a ${CLASS_TOKEN} on top of a white rug"
|
| 78 |
+
"a red ${CLASS_TOKEN}"
|
| 79 |
+
"a purple ${CLASS_TOKEN}"
|
| 80 |
+
"a shiny ${CLASS_TOKEN}"
|
| 81 |
+
"a wet ${CLASS_TOKEN}"
|
| 82 |
+
"a cube shaped ${CLASS_TOKEN}"
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
else
|
| 86 |
+
PROMPT_LIST=(
|
| 87 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} in the jungle."
|
| 88 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} in the snow."
|
| 89 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} on the beach."
|
| 90 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} on a cobblestone street."
|
| 91 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} on top of pink fabric."
|
| 92 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} on top of a wooden floor."
|
| 93 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} with a city in the background."
|
| 94 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} with a mountain in the background."
|
| 95 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} with a blue house in the background."
|
| 96 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} on top of a purple rug in a forest."
|
| 97 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} wearing a red hat."
|
| 98 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} wearing a santa hat."
|
| 99 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} wearing a rainbow scarf."
|
| 100 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} wearing a black top hat and a monocle."
|
| 101 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} in a chef outfit."
|
| 102 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} in a firefighter outfit."
|
| 103 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} in a police outfit."
|
| 104 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} wearing pink glasses."
|
| 105 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} wearing a yellow shirt."
|
| 106 |
+
"a ${UNIQUE_TOKEN} ${CLASS_TOKEN} in a purple wizard outfit."
|
| 107 |
+
"a red ${UNIQUE_TOKEN} ${CLASS_TOKEN}."
|
| 108 |
+
"a purple ${UNIQUE_TOKEN} ${CLASS_TOKEN}."
|
| 109 |
+
"a shiny ${UNIQUE_TOKEN} ${CLASS_TOKEN}."
|
| 110 |
+
"a wet ${UNIQUE_TOKEN} ${CLASS_TOKEN}."
|
| 111 |
+
"a cube shaped ${UNIQUE_TOKEN} ${CLASS_TOKEN}."
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
prompt_test_list=(
|
| 115 |
+
"a ${CLASS_TOKEN} in the jungle"
|
| 116 |
+
"a ${CLASS_TOKEN} in the snow"
|
| 117 |
+
"a ${CLASS_TOKEN} on the beach"
|
| 118 |
+
"a ${CLASS_TOKEN} on a cobblestone street"
|
| 119 |
+
"a ${CLASS_TOKEN} on top of pink fabric"
|
| 120 |
+
"a ${CLASS_TOKEN} on top of a wooden floor"
|
| 121 |
+
"a ${CLASS_TOKEN} with a city in the background"
|
| 122 |
+
"a ${CLASS_TOKEN} with a mountain in the background"
|
| 123 |
+
"a ${CLASS_TOKEN} with a blue house in the background"
|
| 124 |
+
"a ${CLASS_TOKEN} on top of a purple rug in a forest"
|
| 125 |
+
"a ${CLASS_TOKEN} wearing a red hat"
|
| 126 |
+
"a ${CLASS_TOKEN} wearing a santa hat"
|
| 127 |
+
"a ${CLASS_TOKEN} wearing a rainbow scarf"
|
| 128 |
+
"a ${CLASS_TOKEN} wearing a black top hat and a monocle"
|
| 129 |
+
"a ${CLASS_TOKEN} in a chef outfit"
|
| 130 |
+
"a ${CLASS_TOKEN} in a firefighter outfit"
|
| 131 |
+
"a ${CLASS_TOKEN} in a police outfit"
|
| 132 |
+
"a ${CLASS_TOKEN} wearing pink glasses"
|
| 133 |
+
"a ${CLASS_TOKEN} wearing a yellow shirt"
|
| 134 |
+
"a ${CLASS_TOKEN} in a purple wizard outfit"
|
| 135 |
+
"a red ${CLASS_TOKEN}"
|
| 136 |
+
"a purple ${CLASS_TOKEN}"
|
| 137 |
+
"a shiny ${CLASS_TOKEN}"
|
| 138 |
+
"a wet ${CLASS_TOKEN}"
|
| 139 |
+
"a cube shaped ${CLASS_TOKEN}"
|
| 140 |
+
)
|
| 141 |
+
fi
|
| 142 |
+
|
| 143 |
+
VALIDATION_PROMPT=${PROMPT_LIST[@]}
|
| 144 |
+
INSTANCE_PROMPT="a photo of ${UNIQUE_TOKEN} ${CLASS_TOKEN}"
|
| 145 |
+
CLASS_PROMPT="a photo of ${CLASS_TOKEN}"
|
| 146 |
+
|
| 147 |
+
export MODEL_NAME="stabilityai/stable-diffusion-2-1"
|
| 148 |
+
|
| 149 |
+
PEFT_TYPE="hra"
|
| 150 |
+
HRA_R=8
|
| 151 |
+
|
| 152 |
+
export PROJECT_NAME="dreambooth_${PEFT_TYPE}"
|
| 153 |
+
export RUN_NAME="${SELECTED_SUBJECT}_${PEFT_TYPE}_${HRA_R}"
|
| 154 |
+
export INSTANCE_DIR="./data/dreambooth/dataset/${SELECTED_SUBJECT}"
|
| 155 |
+
export CLASS_DIR="./data/class_data/${CLASS_TOKEN}"
|
| 156 |
+
export OUTPUT_DIR="./data/output/${PEFT_TYPE}"
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
accelerate launch train_dreambooth.py \
|
| 160 |
+
--pretrained_model_name_or_path=$MODEL_NAME \
|
| 161 |
+
--instance_data_dir=$INSTANCE_DIR \
|
| 162 |
+
--class_data_dir="$CLASS_DIR" \
|
| 163 |
+
--output_dir=$OUTPUT_DIR \
|
| 164 |
+
--project_name=$PROJECT_NAME \
|
| 165 |
+
--run_name=$RUN_NAME \
|
| 166 |
+
--with_prior_preservation \
|
| 167 |
+
--prior_loss_weight=1.0 \
|
| 168 |
+
--instance_prompt="$INSTANCE_PROMPT" \
|
| 169 |
+
--validation_prompt="$VALIDATION_PROMPT" \
|
| 170 |
+
--class_prompt="$CLASS_PROMPT" \
|
| 171 |
+
--resolution=512 \
|
| 172 |
+
--train_batch_size=1 \
|
| 173 |
+
--num_dataloader_workers=2 \
|
| 174 |
+
--lr_scheduler="constant" \
|
| 175 |
+
--lr_warmup_steps=0 \
|
| 176 |
+
--num_class_images=200 \
|
| 177 |
+
--use_hra \
|
| 178 |
+
--hra_r=$HRA_R \
|
| 179 |
+
--hra_bias="hra_only" \
|
| 180 |
+
--learning_rate=5e-3 \
|
| 181 |
+
--max_train_steps=510 \
|
| 182 |
+
--checkpointing_steps=200 \
|
| 183 |
+
--validation_steps=200 \
|
| 184 |
+
--enable_xformers_memory_efficient_attention \
|
| 185 |
+
--report_to="none" \
|
tasks/tasksmith-ecb1931929df/tests/source/examples/hra_dreambooth/utils/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-ecb1931929df/tests/source/examples/hra_dreambooth/utils/args_loader.py
ADDED
|
@@ -0,0 +1,377 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# adapted from [peft's boft_dreambooth](https://github.com/huggingface/peft/tree/main/examples/boft_dreambooth)
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import os
|
| 5 |
+
import warnings
|
| 6 |
+
from typing import Optional
|
| 7 |
+
|
| 8 |
+
from huggingface_hub import HfFolder, whoami
|
| 9 |
+
from transformers import PretrainedConfig
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def import_model_class_from_model_name_or_path(pretrained_model_name_or_path: str, revision: str):
|
| 13 |
+
text_encoder_config = PretrainedConfig.from_pretrained(
|
| 14 |
+
pretrained_model_name_or_path,
|
| 15 |
+
subfolder="text_encoder",
|
| 16 |
+
revision=revision,
|
| 17 |
+
)
|
| 18 |
+
model_class = text_encoder_config.architectures[0]
|
| 19 |
+
|
| 20 |
+
if model_class == "CLIPTextModel":
|
| 21 |
+
from transformers import CLIPTextModel
|
| 22 |
+
|
| 23 |
+
return CLIPTextModel
|
| 24 |
+
elif model_class == "RobertaSeriesModelWithTransformation":
|
| 25 |
+
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import RobertaSeriesModelWithTransformation
|
| 26 |
+
|
| 27 |
+
return RobertaSeriesModelWithTransformation
|
| 28 |
+
else:
|
| 29 |
+
raise ValueError(f"{model_class} is not supported.")
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def get_full_repo_name(model_id: str, organization: Optional[str] = None, token: Optional[str] = None):
|
| 33 |
+
if token is None:
|
| 34 |
+
token = HfFolder.get_token()
|
| 35 |
+
if organization is None:
|
| 36 |
+
username = whoami(token)["name"]
|
| 37 |
+
return f"{username}/{model_id}"
|
| 38 |
+
else:
|
| 39 |
+
return f"{organization}/{model_id}"
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def parse_args(input_args=None):
|
| 43 |
+
parser = argparse.ArgumentParser(description="Simple example of a Dreambooth training script.")
|
| 44 |
+
parser.add_argument(
|
| 45 |
+
"--pretrained_model_name_or_path",
|
| 46 |
+
type=str,
|
| 47 |
+
default=None,
|
| 48 |
+
required=True,
|
| 49 |
+
help="Path to pretrained model or model identifier from huggingface.co/models.",
|
| 50 |
+
)
|
| 51 |
+
parser.add_argument(
|
| 52 |
+
"--revision",
|
| 53 |
+
type=str,
|
| 54 |
+
default=None,
|
| 55 |
+
required=False,
|
| 56 |
+
help="Revision of pretrained model identifier from huggingface.co/models.",
|
| 57 |
+
)
|
| 58 |
+
parser.add_argument(
|
| 59 |
+
"--tokenizer_name",
|
| 60 |
+
type=str,
|
| 61 |
+
default=None,
|
| 62 |
+
help="Pretrained tokenizer name or path if not the same as model_name",
|
| 63 |
+
)
|
| 64 |
+
parser.add_argument(
|
| 65 |
+
"--instance_data_dir",
|
| 66 |
+
type=str,
|
| 67 |
+
default=None,
|
| 68 |
+
required=True,
|
| 69 |
+
help="A folder containing the training data of instance images.",
|
| 70 |
+
)
|
| 71 |
+
parser.add_argument(
|
| 72 |
+
"--class_data_dir",
|
| 73 |
+
type=str,
|
| 74 |
+
default=None,
|
| 75 |
+
required=False,
|
| 76 |
+
help="A folder containing the training data of class images.",
|
| 77 |
+
)
|
| 78 |
+
parser.add_argument(
|
| 79 |
+
"--instance_prompt",
|
| 80 |
+
type=str,
|
| 81 |
+
default=None,
|
| 82 |
+
required=True,
|
| 83 |
+
help="The prompt with identifier specifying the instance",
|
| 84 |
+
)
|
| 85 |
+
parser.add_argument(
|
| 86 |
+
"--class_prompt",
|
| 87 |
+
type=str,
|
| 88 |
+
default=None,
|
| 89 |
+
help="The prompt to specify images in the same class as provided instance images.",
|
| 90 |
+
)
|
| 91 |
+
parser.add_argument(
|
| 92 |
+
"--with_prior_preservation",
|
| 93 |
+
default=False,
|
| 94 |
+
action="store_true",
|
| 95 |
+
help="Flag to add prior preservation loss.",
|
| 96 |
+
)
|
| 97 |
+
parser.add_argument("--prior_loss_weight", type=float, default=1.0, help="The weight of prior preservation loss.")
|
| 98 |
+
parser.add_argument(
|
| 99 |
+
"--num_class_images",
|
| 100 |
+
type=int,
|
| 101 |
+
default=100,
|
| 102 |
+
help=(
|
| 103 |
+
"Minimal class images for prior preservation loss. If there are not enough images already present in"
|
| 104 |
+
" class_data_dir, additional images will be sampled with class_prompt."
|
| 105 |
+
),
|
| 106 |
+
)
|
| 107 |
+
parser.add_argument(
|
| 108 |
+
"--validation_prompt",
|
| 109 |
+
nargs="+",
|
| 110 |
+
help="A prompt that is used during validation to verify that the model is learning.",
|
| 111 |
+
)
|
| 112 |
+
parser.add_argument(
|
| 113 |
+
"--num_validation_images",
|
| 114 |
+
type=int,
|
| 115 |
+
default=4,
|
| 116 |
+
help="Number of images that should be generated during validation with `validation_prompt`.",
|
| 117 |
+
)
|
| 118 |
+
parser.add_argument(
|
| 119 |
+
"--validation_steps",
|
| 120 |
+
type=int,
|
| 121 |
+
default=500,
|
| 122 |
+
help=(
|
| 123 |
+
"Run dreambooth validation every X steps. Dreambooth validation consists of running the prompt"
|
| 124 |
+
" `args.validation_prompt` multiple times: `args.num_validation_images`."
|
| 125 |
+
),
|
| 126 |
+
)
|
| 127 |
+
parser.add_argument(
|
| 128 |
+
"--output_dir",
|
| 129 |
+
type=str,
|
| 130 |
+
default="text-inversion-model",
|
| 131 |
+
help="The output directory where the model predictions and checkpoints will be written.",
|
| 132 |
+
)
|
| 133 |
+
parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
|
| 134 |
+
parser.add_argument(
|
| 135 |
+
"--resolution",
|
| 136 |
+
type=int,
|
| 137 |
+
default=512,
|
| 138 |
+
help=(
|
| 139 |
+
"The resolution for input images, all the images in the train/validation dataset will be resized to this"
|
| 140 |
+
" resolution"
|
| 141 |
+
),
|
| 142 |
+
)
|
| 143 |
+
parser.add_argument(
|
| 144 |
+
"--center_crop", action="store_true", help="Whether to center crop images before resizing to resolution"
|
| 145 |
+
)
|
| 146 |
+
parser.add_argument("--train_text_encoder", action="store_true", help="Whether to train the text encoder")
|
| 147 |
+
|
| 148 |
+
parser.add_argument(
|
| 149 |
+
"--set_grads_to_none",
|
| 150 |
+
action="store_true",
|
| 151 |
+
help=(
|
| 152 |
+
"Save more memory by using setting grads to None instead of zero. Be aware, that this changes certain"
|
| 153 |
+
" behaviors, so disable this argument if it causes any problems. More info:"
|
| 154 |
+
" https://pytorch.org/docs/stable/generated/torch.optim.Optimizer.zero_grad.html"
|
| 155 |
+
),
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
# hra args
|
| 159 |
+
parser.add_argument("--use_hra", action="store_true", help="Whether to use HRA for parameter efficient tuning.")
|
| 160 |
+
parser.add_argument("--hra_r", type=int, default=8, help="The rank of HRA across different layers.")
|
| 161 |
+
parser.add_argument(
|
| 162 |
+
"--hra_apply_GS", default=False, action="store_true", help="Whether to apply Gram-Schmidt orthogonalization."
|
| 163 |
+
)
|
| 164 |
+
parser.add_argument(
|
| 165 |
+
"--hra_bias",
|
| 166 |
+
type=str,
|
| 167 |
+
default="none",
|
| 168 |
+
help="Bias type for HRA. Can be 'none', 'all' or 'hra_only', only used if use_hra is True.",
|
| 169 |
+
)
|
| 170 |
+
parser.add_argument(
|
| 171 |
+
"--num_dataloader_workers", type=int, default=1, help="Num of workers for the training dataloader."
|
| 172 |
+
)
|
| 173 |
+
parser.add_argument(
|
| 174 |
+
"--no_tracemalloc",
|
| 175 |
+
default=False,
|
| 176 |
+
action="store_true",
|
| 177 |
+
help="Flag to stop memory allocation tracing during training. This could speed up training on Windows.",
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
parser.add_argument(
|
| 181 |
+
"--train_batch_size", type=int, default=4, help="Batch size (per device) for the training dataloader."
|
| 182 |
+
)
|
| 183 |
+
parser.add_argument(
|
| 184 |
+
"--sample_batch_size", type=int, default=4, help="Batch size (per device) for sampling images."
|
| 185 |
+
)
|
| 186 |
+
parser.add_argument("--num_train_epochs", type=int, default=1)
|
| 187 |
+
parser.add_argument(
|
| 188 |
+
"--max_train_steps",
|
| 189 |
+
type=int,
|
| 190 |
+
default=None,
|
| 191 |
+
help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
|
| 192 |
+
)
|
| 193 |
+
parser.add_argument(
|
| 194 |
+
"--checkpointing_steps",
|
| 195 |
+
type=int,
|
| 196 |
+
default=500,
|
| 197 |
+
help=(
|
| 198 |
+
"Save a checkpoint of the training state every X updates. These checkpoints can be used both as final"
|
| 199 |
+
" checkpoints in case they are better than the last checkpoint, and are also suitable for resuming"
|
| 200 |
+
" training using `--resume_from_checkpoint`."
|
| 201 |
+
),
|
| 202 |
+
)
|
| 203 |
+
parser.add_argument(
|
| 204 |
+
"--resume_from_checkpoint",
|
| 205 |
+
type=str,
|
| 206 |
+
default=None,
|
| 207 |
+
help=(
|
| 208 |
+
"Whether training should be resumed from a previous checkpoint. Use a path saved by"
|
| 209 |
+
' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
|
| 210 |
+
),
|
| 211 |
+
)
|
| 212 |
+
parser.add_argument(
|
| 213 |
+
"--gradient_accumulation_steps",
|
| 214 |
+
type=int,
|
| 215 |
+
default=1,
|
| 216 |
+
help="Number of updates steps to accumulate before performing a backward/update pass.",
|
| 217 |
+
)
|
| 218 |
+
parser.add_argument(
|
| 219 |
+
"--gradient_checkpointing",
|
| 220 |
+
action="store_true",
|
| 221 |
+
help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
|
| 222 |
+
)
|
| 223 |
+
parser.add_argument(
|
| 224 |
+
"--learning_rate",
|
| 225 |
+
type=float,
|
| 226 |
+
default=5e-6,
|
| 227 |
+
help="Initial learning rate (after the potential warmup period) to use.",
|
| 228 |
+
)
|
| 229 |
+
parser.add_argument(
|
| 230 |
+
"--scale_lr",
|
| 231 |
+
action="store_true",
|
| 232 |
+
default=False,
|
| 233 |
+
help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
|
| 234 |
+
)
|
| 235 |
+
parser.add_argument(
|
| 236 |
+
"--lr_scheduler",
|
| 237 |
+
type=str,
|
| 238 |
+
default="constant",
|
| 239 |
+
help=(
|
| 240 |
+
'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
|
| 241 |
+
' "constant", "constant_with_warmup"]'
|
| 242 |
+
),
|
| 243 |
+
)
|
| 244 |
+
parser.add_argument(
|
| 245 |
+
"--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
|
| 246 |
+
)
|
| 247 |
+
parser.add_argument(
|
| 248 |
+
"--lr_num_cycles",
|
| 249 |
+
type=int,
|
| 250 |
+
default=1,
|
| 251 |
+
help="Number of hard resets of the lr in cosine_with_restarts scheduler.",
|
| 252 |
+
)
|
| 253 |
+
parser.add_argument("--lr_power", type=float, default=1.0, help="Power factor of the polynomial scheduler.")
|
| 254 |
+
parser.add_argument(
|
| 255 |
+
"--use_8bit_adam", action="store_true", help="Whether or not to use 8-bit Adam from bitsandbytes."
|
| 256 |
+
)
|
| 257 |
+
parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
|
| 258 |
+
parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
|
| 259 |
+
parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
|
| 260 |
+
parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
|
| 261 |
+
parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
|
| 262 |
+
parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
|
| 263 |
+
parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
|
| 264 |
+
parser.add_argument(
|
| 265 |
+
"--hub_model_id",
|
| 266 |
+
type=str,
|
| 267 |
+
default=None,
|
| 268 |
+
help="The name of the repository to keep in sync with the local `output_dir`.",
|
| 269 |
+
)
|
| 270 |
+
parser.add_argument(
|
| 271 |
+
"--logging_dir",
|
| 272 |
+
type=str,
|
| 273 |
+
default="logs",
|
| 274 |
+
help=(
|
| 275 |
+
"[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
|
| 276 |
+
" *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
|
| 277 |
+
),
|
| 278 |
+
)
|
| 279 |
+
parser.add_argument(
|
| 280 |
+
"--allow_tf32",
|
| 281 |
+
action="store_true",
|
| 282 |
+
help=(
|
| 283 |
+
"Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
|
| 284 |
+
" https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
|
| 285 |
+
),
|
| 286 |
+
)
|
| 287 |
+
parser.add_argument(
|
| 288 |
+
"--project_name",
|
| 289 |
+
type=str,
|
| 290 |
+
default=None,
|
| 291 |
+
help=("The project name for log tracking"),
|
| 292 |
+
)
|
| 293 |
+
parser.add_argument(
|
| 294 |
+
"--run_name",
|
| 295 |
+
type=str,
|
| 296 |
+
default=None,
|
| 297 |
+
help=("The run name for log tracking"),
|
| 298 |
+
)
|
| 299 |
+
parser.add_argument(
|
| 300 |
+
"--report_to",
|
| 301 |
+
type=str,
|
| 302 |
+
default="wandb",
|
| 303 |
+
help=(
|
| 304 |
+
'The integration to report the results and logs to. Supported platforms are `"wandb"`'
|
| 305 |
+
' (default), `"tensorboard"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
|
| 306 |
+
),
|
| 307 |
+
)
|
| 308 |
+
parser.add_argument(
|
| 309 |
+
"--wandb_key",
|
| 310 |
+
type=str,
|
| 311 |
+
default=None,
|
| 312 |
+
help=("If report to option is set to wandb, api-key for wandb used for login to wandb "),
|
| 313 |
+
)
|
| 314 |
+
parser.add_argument(
|
| 315 |
+
"--wandb_project_name",
|
| 316 |
+
type=str,
|
| 317 |
+
default=None,
|
| 318 |
+
help=("If report to option is set to wandb, project name in wandb for log tracking "),
|
| 319 |
+
)
|
| 320 |
+
parser.add_argument(
|
| 321 |
+
"--wandb_run_name",
|
| 322 |
+
type=str,
|
| 323 |
+
default=None,
|
| 324 |
+
help=("If report to option is set to wandb, project name in wandb for log tracking "),
|
| 325 |
+
)
|
| 326 |
+
parser.add_argument(
|
| 327 |
+
"--mixed_precision",
|
| 328 |
+
type=str,
|
| 329 |
+
default=None,
|
| 330 |
+
choices=["no", "fp16", "bf16"],
|
| 331 |
+
help=(
|
| 332 |
+
"Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
|
| 333 |
+
" 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
|
| 334 |
+
" flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
|
| 335 |
+
),
|
| 336 |
+
)
|
| 337 |
+
parser.add_argument(
|
| 338 |
+
"--prior_generation_precision",
|
| 339 |
+
type=str,
|
| 340 |
+
default=None,
|
| 341 |
+
choices=["no", "fp32", "fp16", "bf16"],
|
| 342 |
+
help=(
|
| 343 |
+
"Choose prior generation precision between fp32, fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
|
| 344 |
+
" 1.10.and an Nvidia Ampere GPU. Default to fp16 if a GPU is available else fp32."
|
| 345 |
+
),
|
| 346 |
+
)
|
| 347 |
+
parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
|
| 348 |
+
parser.add_argument(
|
| 349 |
+
"--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."
|
| 350 |
+
)
|
| 351 |
+
|
| 352 |
+
if input_args is not None:
|
| 353 |
+
args = parser.parse_args(input_args)
|
| 354 |
+
else:
|
| 355 |
+
args = parser.parse_args()
|
| 356 |
+
|
| 357 |
+
env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
|
| 358 |
+
if env_local_rank != -1 and env_local_rank != args.local_rank:
|
| 359 |
+
args.local_rank = env_local_rank
|
| 360 |
+
|
| 361 |
+
# Sanity checks
|
| 362 |
+
# if args.dataset_name is None and args.train_data_dir is None:
|
| 363 |
+
# raise ValueError("Need either a dataset name or a training folder.")
|
| 364 |
+
|
| 365 |
+
if args.with_prior_preservation:
|
| 366 |
+
if args.class_data_dir is None:
|
| 367 |
+
raise ValueError("You must specify a data directory for class images.")
|
| 368 |
+
if args.class_prompt is None:
|
| 369 |
+
raise ValueError("You must specify prompt for class images.")
|
| 370 |
+
else:
|
| 371 |
+
# logger is not available yet
|
| 372 |
+
if args.class_data_dir is not None:
|
| 373 |
+
warnings.warn("You need not use --class_data_dir without --with_prior_preservation.")
|
| 374 |
+
if args.class_prompt is not None:
|
| 375 |
+
warnings.warn("You need not use --class_prompt without --with_prior_preservation.")
|
| 376 |
+
|
| 377 |
+
return args
|
tasks/tasksmith-ecb1931929df/tests/source/examples/hra_dreambooth/utils/dataset.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# adapted from [peft's boft_dreambooth](https://github.com/huggingface/peft/tree/main/examples/boft_dreambooth)
|
| 2 |
+
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
from PIL import Image
|
| 7 |
+
from torch.utils.data import Dataset
|
| 8 |
+
from torchvision import transforms
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class DreamBoothDataset(Dataset):
|
| 12 |
+
"""
|
| 13 |
+
A dataset to prepare the instance and class images with the prompts for fine-tuning the model.
|
| 14 |
+
It pre-processes the images and the tokenizes prompts.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
def __init__(
|
| 18 |
+
self,
|
| 19 |
+
instance_data_root,
|
| 20 |
+
instance_prompt,
|
| 21 |
+
tokenizer,
|
| 22 |
+
class_data_root=None,
|
| 23 |
+
class_prompt=None,
|
| 24 |
+
size=512,
|
| 25 |
+
center_crop=False,
|
| 26 |
+
):
|
| 27 |
+
self.size = size
|
| 28 |
+
self.center_crop = center_crop
|
| 29 |
+
self.tokenizer = tokenizer
|
| 30 |
+
|
| 31 |
+
self.instance_data_root = Path(instance_data_root)
|
| 32 |
+
if not self.instance_data_root.exists():
|
| 33 |
+
raise ValueError("Instance images root doesn't exists.")
|
| 34 |
+
|
| 35 |
+
self.instance_images_path = list(Path(instance_data_root).iterdir())
|
| 36 |
+
self.num_instance_images = len(self.instance_images_path)
|
| 37 |
+
self.instance_prompt = instance_prompt
|
| 38 |
+
self._length = self.num_instance_images
|
| 39 |
+
|
| 40 |
+
if class_data_root is not None:
|
| 41 |
+
self.class_data_root = Path(class_data_root)
|
| 42 |
+
self.class_data_root.mkdir(parents=True, exist_ok=True)
|
| 43 |
+
self.class_images_path = list(self.class_data_root.iterdir())
|
| 44 |
+
self.num_class_images = len(self.class_images_path)
|
| 45 |
+
self._length = max(self.num_class_images, self.num_instance_images)
|
| 46 |
+
self.class_prompt = class_prompt
|
| 47 |
+
else:
|
| 48 |
+
self.class_data_root = None
|
| 49 |
+
|
| 50 |
+
self.image_transforms = transforms.Compose(
|
| 51 |
+
[
|
| 52 |
+
transforms.Resize(size, interpolation=transforms.InterpolationMode.BILINEAR),
|
| 53 |
+
transforms.CenterCrop(size) if center_crop else transforms.RandomCrop(size),
|
| 54 |
+
transforms.ToTensor(),
|
| 55 |
+
transforms.Normalize([0.5], [0.5]),
|
| 56 |
+
]
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
def __len__(self):
|
| 60 |
+
return self._length
|
| 61 |
+
|
| 62 |
+
def __getitem__(self, index):
|
| 63 |
+
example = {}
|
| 64 |
+
instance_image = Image.open(self.instance_images_path[index % self.num_instance_images])
|
| 65 |
+
if not instance_image.mode == "RGB":
|
| 66 |
+
instance_image = instance_image.convert("RGB")
|
| 67 |
+
example["instance_images"] = self.image_transforms(instance_image)
|
| 68 |
+
example["instance_prompt_ids"] = self.tokenizer(
|
| 69 |
+
self.instance_prompt,
|
| 70 |
+
truncation=True,
|
| 71 |
+
padding="max_length",
|
| 72 |
+
max_length=self.tokenizer.model_max_length,
|
| 73 |
+
return_tensors="pt",
|
| 74 |
+
).input_ids
|
| 75 |
+
|
| 76 |
+
if self.class_data_root:
|
| 77 |
+
class_image = Image.open(self.class_images_path[index % self.num_class_images])
|
| 78 |
+
if not class_image.mode == "RGB":
|
| 79 |
+
class_image = class_image.convert("RGB")
|
| 80 |
+
example["class_images"] = self.image_transforms(class_image)
|
| 81 |
+
example["class_prompt_ids"] = self.tokenizer(
|
| 82 |
+
self.class_prompt,
|
| 83 |
+
truncation=True,
|
| 84 |
+
padding="max_length",
|
| 85 |
+
max_length=self.tokenizer.model_max_length,
|
| 86 |
+
return_tensors="pt",
|
| 87 |
+
).input_ids
|
| 88 |
+
|
| 89 |
+
return example
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def collate_fn(examples, with_prior_preservation=False):
|
| 93 |
+
input_ids = [example["instance_prompt_ids"] for example in examples]
|
| 94 |
+
pixel_values = [example["instance_images"] for example in examples]
|
| 95 |
+
|
| 96 |
+
# Concat class and instance examples for prior preservation.
|
| 97 |
+
# We do this to avoid doing two forward passes.
|
| 98 |
+
if with_prior_preservation:
|
| 99 |
+
input_ids += [example["class_prompt_ids"] for example in examples]
|
| 100 |
+
pixel_values += [example["class_images"] for example in examples]
|
| 101 |
+
|
| 102 |
+
pixel_values = torch.stack(pixel_values)
|
| 103 |
+
pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float()
|
| 104 |
+
|
| 105 |
+
input_ids = torch.cat(input_ids, dim=0)
|
| 106 |
+
|
| 107 |
+
batch = {
|
| 108 |
+
"input_ids": input_ids,
|
| 109 |
+
"pixel_values": pixel_values,
|
| 110 |
+
}
|
| 111 |
+
return batch
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
class PromptDataset(Dataset):
|
| 115 |
+
"A simple dataset to prepare the prompts to generate class images on multiple GPUs."
|
| 116 |
+
|
| 117 |
+
def __init__(self, prompt, num_samples):
|
| 118 |
+
self.prompt = prompt
|
| 119 |
+
self.num_samples = num_samples
|
| 120 |
+
|
| 121 |
+
def __len__(self):
|
| 122 |
+
return self.num_samples
|
| 123 |
+
|
| 124 |
+
def __getitem__(self, index):
|
| 125 |
+
example = {}
|
| 126 |
+
example["prompt"] = self.prompt
|
| 127 |
+
example["index"] = index
|
| 128 |
+
return example
|
tasks/tasksmith-ecb1931929df/tests/source/examples/hra_dreambooth/utils/tracemalloc.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# adapted from [peft's boft_dreambooth](https://github.com/huggingface/peft/tree/main/examples/boft_dreambooth)
|
| 2 |
+
|
| 3 |
+
import gc
|
| 4 |
+
import threading
|
| 5 |
+
|
| 6 |
+
import psutil
|
| 7 |
+
import torch
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
# Converting Bytes to Megabytes
|
| 11 |
+
def b2mb(x):
|
| 12 |
+
return int(x / 2**20)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
# This context manager is used to track the peak memory usage of the process
|
| 16 |
+
class TorchTracemalloc:
|
| 17 |
+
def __enter__(self):
|
| 18 |
+
self.device_type = torch.accelerator.current_accelerator().type if hasattr(torch, "accelerator") else "cuda"
|
| 19 |
+
self.device_module = getattr(torch, self.device_type, torch.cuda)
|
| 20 |
+
gc.collect()
|
| 21 |
+
self.device_module.empty_cache()
|
| 22 |
+
self.device_module.reset_peak_memory_stats() # reset the peak gauge to zero
|
| 23 |
+
self.begin = self.device_module.memory_allocated()
|
| 24 |
+
self.process = psutil.Process()
|
| 25 |
+
|
| 26 |
+
self.cpu_begin = self.cpu_mem_used()
|
| 27 |
+
self.peak_monitoring = True
|
| 28 |
+
peak_monitor_thread = threading.Thread(target=self.peak_monitor_func)
|
| 29 |
+
peak_monitor_thread.daemon = True
|
| 30 |
+
peak_monitor_thread.start()
|
| 31 |
+
return self
|
| 32 |
+
|
| 33 |
+
def cpu_mem_used(self):
|
| 34 |
+
"""get resident set size memory for the current process"""
|
| 35 |
+
return self.process.memory_info().rss
|
| 36 |
+
|
| 37 |
+
def peak_monitor_func(self):
|
| 38 |
+
self.cpu_peak = -1
|
| 39 |
+
|
| 40 |
+
while True:
|
| 41 |
+
self.cpu_peak = max(self.cpu_mem_used(), self.cpu_peak)
|
| 42 |
+
|
| 43 |
+
# can't sleep or will not catch the peak right (this comment is here on purpose)
|
| 44 |
+
# time.sleep(0.001) # 1msec
|
| 45 |
+
|
| 46 |
+
if not self.peak_monitoring:
|
| 47 |
+
break
|
| 48 |
+
|
| 49 |
+
def __exit__(self, *exc):
|
| 50 |
+
self.peak_monitoring = False
|
| 51 |
+
|
| 52 |
+
gc.collect()
|
| 53 |
+
self.device_module.empty_cache()
|
| 54 |
+
self.end = self.device_module.memory_allocated()
|
| 55 |
+
self.peak = self.device_module.max_memory_allocated()
|
| 56 |
+
self.used = b2mb(self.end - self.begin)
|
| 57 |
+
self.peaked = b2mb(self.peak - self.begin)
|
| 58 |
+
|
| 59 |
+
self.cpu_end = self.cpu_mem_used()
|
| 60 |
+
self.cpu_used = b2mb(self.cpu_end - self.cpu_begin)
|
| 61 |
+
self.cpu_peaked = b2mb(self.cpu_peak - self.cpu_begin)
|
| 62 |
+
# print(f"delta used/peak {self.used:4d}/{self.peaked:4d}")
|
tasks/tasksmith-ecb1931929df/tests/source/examples/image_classification/README.md
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Fine-tuning for image classification using LoRA and 🤗 PEFT
|
| 2 |
+
|
| 3 |
+
## Vision Transformer model from transformers
|
| 4 |
+
|
| 5 |
+
[](https://colab.research.google.com/github/huggingface/peft/blob/main/examples/image_classification/image_classification_peft_lora.ipynb)
|
| 6 |
+
|
| 7 |
+
We provide a notebook (`image_classification_peft_lora.ipynb`) where we learn how to use [LoRA](https://huggingface.co/papers/2106.09685) from 🤗 PEFT to fine-tune an image classification model by ONLY using **0.7%** of the original trainable parameters of the model.
|
| 8 |
+
|
| 9 |
+
LoRA adds low-rank "update matrices" to certain blocks in the underlying model (in this case the attention blocks) and ONLY trains those matrices during fine-tuning. During inference, these update matrices are _merged_ with the original model parameters. For more details, check out the [original LoRA paper](https://huggingface.co/papers/2106.09685).
|
| 10 |
+
|
| 11 |
+
## PoolFormer model from timm
|
| 12 |
+
|
| 13 |
+
[](https://colab.research.google.com/github/huggingface/peft/blob/main/examples/image_classification/image_classification_timm_peft_lora.ipynb)
|
| 14 |
+
|
| 15 |
+
The notebook `image_classification_timm_peft_lora.ipynb` showcases fine-tuning an image classification model using from the [timm](https://huggingface.co/docs/timm/index) library. Again, LoRA is used to reduce the numberof trainable parameters to a fraction of the total.
|
tasks/tasksmith-ecb1931929df/tests/source/examples/image_classification/image_classification_peft_lora.ipynb
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tasks/tasksmith-ecb1931929df/tests/source/examples/image_classification/image_classification_timm_peft_lora.ipynb
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tasks/tasksmith-ecb1931929df/tests/source/examples/int8_training/Finetune_flan_t5_large_bnb_peft.ipynb
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tasks/tasksmith-ecb1931929df/tests/source/examples/int8_training/Finetune_opt_bnb_peft.ipynb
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tasks/tasksmith-ecb1931929df/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-ecb1931929df/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,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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(0, 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().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-ecb1931929df/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-ecb1931929df/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-ecb1931929df/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
|