mirror of
https://github.com/wassname/peft.git
synced 2026-09-25 13:50:20 +08:00
416 lines
13 KiB
Plaintext
416 lines
13 KiB
Plaintext
{
|
|
"cells": [
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 17,
|
|
"id": "5f93b7d1",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"from transformers import AutoModelForSeq2SeqLM\n",
|
|
"from pet import get_pet_config,get_pet_model, get_pet_model_state_dict\n",
|
|
"import torch\n",
|
|
"from datasets import load_dataset\n",
|
|
"import os\n",
|
|
"os.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\"\n",
|
|
"from transformers import AutoTokenizer\n",
|
|
"from torch.utils.data import DataLoader\n",
|
|
"from transformers import default_data_collator,get_linear_schedule_with_warmup\n",
|
|
"from tqdm import tqdm\n",
|
|
"from datasets import load_dataset\n",
|
|
"\n",
|
|
"device = \"cuda\"\n",
|
|
"model_name_or_path = \"bigscience/mt0-large\"\n",
|
|
"tokenizer_name_or_path = \"bigscience/mt0-large\"\n",
|
|
"\n",
|
|
"config = {\n",
|
|
" \"pet_type\":\"LORA\",\n",
|
|
" \"task_type\":\"SEQ_2_SEQ_LM\",\n",
|
|
" \"r\":16,\n",
|
|
" \"lora_alpha\": 32,\n",
|
|
" \"lora_dropout\": 0.1\n",
|
|
"}\n",
|
|
"checkpoint_name = \"financial_sentiment_analysis_lora_v1.pt\"\n",
|
|
"text_column = \"sentence\"\n",
|
|
"label_column = \"text_label\"\n",
|
|
"max_length=128\n",
|
|
"lr = 1e-3\n",
|
|
"num_epochs = 3\n",
|
|
"batch_size=8\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "8d0850ac",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# creating model\n",
|
|
"pet_config = get_pet_config(config)\n",
|
|
"\n",
|
|
"model = AutoModelForSeq2SeqLM.from_pretrained(model_name_or_path)\n",
|
|
"model = get_pet_model(model, pet_config)\n",
|
|
"model.print_trainable_parameters()\n",
|
|
"model"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 3,
|
|
"id": "4ee2babf",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stderr",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"/home/sourab/miniconda3/envs/ml/lib/python3.10/site-packages/huggingface_hub/utils/_deprecation.py:97: FutureWarning: Deprecated argument(s) used in 'dataset_info': token. Will not be supported from version '0.12'.\n",
|
|
" warnings.warn(message, FutureWarning)\n",
|
|
"Found cached dataset financial_phrasebank (/home/sourab/.cache/huggingface/datasets/financial_phrasebank/sentences_allagree/1.0.0/550bde12e6c30e2674da973a55f57edde5181d53f5a5a34c1531c53f93b7e141)\n"
|
|
]
|
|
},
|
|
{
|
|
"data": {
|
|
"application/vnd.jupyter.widget-view+json": {
|
|
"model_id": "6de075f8208349108291ac5ab7f5c980",
|
|
"version_major": 2,
|
|
"version_minor": 0
|
|
},
|
|
"text/plain": [
|
|
" 0%| | 0/1 [00:00<?, ?it/s]"
|
|
]
|
|
},
|
|
"metadata": {},
|
|
"output_type": "display_data"
|
|
},
|
|
{
|
|
"data": {
|
|
"application/vnd.jupyter.widget-view+json": {
|
|
"model_id": "4b0e67b6d93f43e4b0f6a2f8978e4b0c",
|
|
"version_major": 2,
|
|
"version_minor": 0
|
|
},
|
|
"text/plain": [
|
|
" 0%| | 0/3 [00:00<?, ?ba/s]"
|
|
]
|
|
},
|
|
"metadata": {},
|
|
"output_type": "display_data"
|
|
},
|
|
{
|
|
"data": {
|
|
"application/vnd.jupyter.widget-view+json": {
|
|
"model_id": "a9551029c9884529bda7421a99170b51",
|
|
"version_major": 2,
|
|
"version_minor": 0
|
|
},
|
|
"text/plain": [
|
|
" 0%| | 0/1 [00:00<?, ?ba/s]"
|
|
]
|
|
},
|
|
"metadata": {},
|
|
"output_type": "display_data"
|
|
},
|
|
{
|
|
"data": {
|
|
"text/plain": [
|
|
"{'sentence': 'The order was valued at USD12 .2 m.',\n",
|
|
" 'label': 1,\n",
|
|
" 'text_label': 'neutral'}"
|
|
]
|
|
},
|
|
"execution_count": 3,
|
|
"metadata": {},
|
|
"output_type": "execute_result"
|
|
}
|
|
],
|
|
"source": [
|
|
"# loading dataset\n",
|
|
"dataset = load_dataset(\"financial_phrasebank\", 'sentences_allagree')\n",
|
|
"dataset = dataset[\"train\"].train_test_split(test_size=0.1)\n",
|
|
"dataset[\"validation\"] = dataset[\"test\"]\n",
|
|
"del(dataset[\"test\"])\n",
|
|
"\n",
|
|
"classes = dataset[\"train\"].features[\"label\"].names\n",
|
|
"dataset = dataset.map(\n",
|
|
" lambda x: {\"text_label\": [classes[label] for label in x[\"label\"]]},\n",
|
|
" batched=True,\n",
|
|
" num_proc=1,\n",
|
|
" \n",
|
|
")\n",
|
|
"\n",
|
|
"dataset[\"train\"][0]"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 4,
|
|
"id": "adf9608c",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"data": {
|
|
"application/vnd.jupyter.widget-view+json": {
|
|
"model_id": "4421971232434db1b6141e91fda2f6d7",
|
|
"version_major": 2,
|
|
"version_minor": 0
|
|
},
|
|
"text/plain": [
|
|
"Running tokenizer on dataset: 0%| | 0/3 [00:00<?, ?ba/s]"
|
|
]
|
|
},
|
|
"metadata": {},
|
|
"output_type": "display_data"
|
|
},
|
|
{
|
|
"data": {
|
|
"application/vnd.jupyter.widget-view+json": {
|
|
"model_id": "9b2ef793d93443949f4a5d5874d4bc05",
|
|
"version_major": 2,
|
|
"version_minor": 0
|
|
},
|
|
"text/plain": [
|
|
"Running tokenizer on dataset: 0%| | 0/1 [00:00<?, ?ba/s]"
|
|
]
|
|
},
|
|
"metadata": {},
|
|
"output_type": "display_data"
|
|
}
|
|
],
|
|
"source": [
|
|
"# data preprocessing\n",
|
|
"tokenizer = AutoTokenizer.from_pretrained(model_name_or_path)\n",
|
|
"def preprocess_function(examples):\n",
|
|
" inputs = examples[text_column]\n",
|
|
" targets = examples[label_column]\n",
|
|
" model_inputs = tokenizer(inputs, max_length=max_length, padding=\"max_length\", truncation=True, return_tensors=\"pt\")\n",
|
|
" labels = tokenizer(targets, max_length=3, padding=\"max_length\", truncation=True, return_tensors=\"pt\")\n",
|
|
" labels = labels[\"input_ids\"]\n",
|
|
" labels[labels==tokenizer.pad_token_id] = -100\n",
|
|
" model_inputs[\"labels\"] = labels\n",
|
|
" return model_inputs\n",
|
|
"\n",
|
|
"processed_datasets = dataset.map(\n",
|
|
" preprocess_function,\n",
|
|
" batched=True,\n",
|
|
" num_proc=1,\n",
|
|
" remove_columns=dataset[\"train\"].column_names,\n",
|
|
" load_from_cache_file=False,\n",
|
|
" desc=\"Running tokenizer on dataset\",\n",
|
|
" )\n",
|
|
"\n",
|
|
"train_dataset = processed_datasets[\"train\"]\n",
|
|
"eval_dataset = processed_datasets[\"validation\"]\n",
|
|
"\n",
|
|
"train_dataloader = DataLoader(\n",
|
|
" train_dataset, shuffle=True, collate_fn=default_data_collator, batch_size=batch_size, pin_memory=True\n",
|
|
" )\n",
|
|
"eval_dataloader = DataLoader(eval_dataset, collate_fn=default_data_collator, batch_size=batch_size, pin_memory=True)\n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
" "
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 5,
|
|
"id": "f733a3c6",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# optimizer and lr scheduler\n",
|
|
"optimizer = torch.optim.AdamW(model.parameters(), lr=lr)\n",
|
|
"lr_scheduler = get_linear_schedule_with_warmup(\n",
|
|
" optimizer=optimizer,\n",
|
|
" num_warmup_steps=0,\n",
|
|
" num_training_steps=(len(train_dataloader) * num_epochs),\n",
|
|
")\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 6,
|
|
"id": "6b3a4090",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stderr",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"100%|█████████████████████████████████████████████████████████████| 255/255 [00:53<00:00, 4.80it/s]\n",
|
|
"100%|███████████████████████████████████████████████████████████████| 29/29 [00:02<00:00, 14.16it/s]\n"
|
|
]
|
|
},
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"epoch=0: train_ppl=tensor(13.6966, device='cuda:0') train_epoch_loss=tensor(2.6171, device='cuda:0') eval_ppl=tensor(1.0046, device='cuda:0') eval_epoch_loss=tensor(0.0046, device='cuda:0')\n"
|
|
]
|
|
},
|
|
{
|
|
"name": "stderr",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"100%|█████████████████████████████████████████████████████████████| 255/255 [00:52<00:00, 4.88it/s]\n",
|
|
"100%|███████████████████████████████████████████████████████████████| 29/29 [00:02<00:00, 14.20it/s]\n"
|
|
]
|
|
},
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"epoch=1: train_ppl=tensor(1.5893, device='cuda:0') train_epoch_loss=tensor(0.4633, device='cuda:0') eval_ppl=tensor(1.0020, device='cuda:0') eval_epoch_loss=tensor(0.0020, device='cuda:0')\n"
|
|
]
|
|
},
|
|
{
|
|
"name": "stderr",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"100%|█████████████████████████████████████████████████████████████| 255/255 [00:52<00:00, 4.87it/s]\n",
|
|
"100%|███████████████████████████████████████████████████████████████| 29/29 [00:02<00:00, 14.18it/s]\n"
|
|
]
|
|
},
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"epoch=2: train_ppl=tensor(1.3210, device='cuda:0') train_epoch_loss=tensor(0.2784, device='cuda:0') eval_ppl=tensor(1.0026, device='cuda:0') eval_epoch_loss=tensor(0.0026, device='cuda:0')\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"# training and evaluation\n",
|
|
"model = model.to(device)\n",
|
|
"\n",
|
|
"for epoch in range(num_epochs):\n",
|
|
" model.train()\n",
|
|
" total_loss = 0\n",
|
|
" for step, batch in enumerate(tqdm(train_dataloader)):\n",
|
|
" batch = {k: v.to(device) for k, v in batch.items()}\n",
|
|
" outputs = model(**batch)\n",
|
|
" loss = outputs.loss\n",
|
|
" total_loss += loss.detach().float()\n",
|
|
" loss.backward()\n",
|
|
" optimizer.step()\n",
|
|
" lr_scheduler.step()\n",
|
|
" optimizer.zero_grad()\n",
|
|
"\n",
|
|
" model.eval()\n",
|
|
" eval_loss = 0\n",
|
|
" eval_preds = []\n",
|
|
" for step, batch in enumerate(tqdm(eval_dataloader)):\n",
|
|
" batch = {k: v.to(device) for k, v in batch.items()}\n",
|
|
" with torch.no_grad():\n",
|
|
" outputs = model(**batch)\n",
|
|
" loss = outputs.loss\n",
|
|
" eval_loss += loss.detach().float()\n",
|
|
" eval_preds.extend(tokenizer.batch_decode(torch.argmax(outputs.logits, -1).detach().cpu().numpy(), skip_special_tokens=True))\n",
|
|
"\n",
|
|
" eval_epoch_loss = eval_loss/len(train_dataloader)\n",
|
|
" eval_ppl = torch.exp(eval_epoch_loss)\n",
|
|
" train_epoch_loss = total_loss/len(eval_dataloader)\n",
|
|
" train_ppl = torch.exp(train_epoch_loss)\n",
|
|
" print(f\"{epoch=}: {train_ppl=} {train_epoch_loss=} {eval_ppl=} {eval_epoch_loss=}\")\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 20,
|
|
"id": "6cafa67b",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"accuracy=98.23788546255507 % on the evaluation dataset\n",
|
|
"eval_preds[:10]=['neutral', 'neutral', 'positive', 'positive', 'neutral', 'neutral', 'neutral', 'neutral', 'neutral', 'neutral']\n",
|
|
"dataset['validation']['text_label'][:10]=['neutral', 'neutral', 'positive', 'positive', 'neutral', 'neutral', 'neutral', 'neutral', 'neutral', 'neutral']\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"# print accuracy\n",
|
|
"correct =0\n",
|
|
"total = 0\n",
|
|
"for pred,true in zip(eval_preds, dataset[\"validation\"][\"text_label\"]):\n",
|
|
" if pred.strip()==true.strip():\n",
|
|
" correct+=1\n",
|
|
" total+=1 \n",
|
|
"accuracy = correct/total*100\n",
|
|
"print(f\"{accuracy=} % on the evaluation dataset\")\n",
|
|
"print(f\"{eval_preds[:10]=}\")\n",
|
|
"print(f\"{dataset['validation']['text_label'][:10]=}\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "a8de6005",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# saving model\n",
|
|
"state_dict = get_pet_model_state_dict(model)\n",
|
|
"torch.save(state_dict, checkpoint_name)\n",
|
|
"print(state_dict)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 18,
|
|
"id": "bd20cd4c",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"19M\tfinancial_sentiment_analysis_lora_v1.pt\r\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"!du -h $checkpoint_name"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "76c2fc29",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": []
|
|
}
|
|
],
|
|
"metadata": {
|
|
"kernelspec": {
|
|
"display_name": "Python 3.10.5 64-bit",
|
|
"language": "python",
|
|
"name": "python3"
|
|
},
|
|
"language_info": {
|
|
"codemirror_mode": {
|
|
"name": "ipython",
|
|
"version": 3
|
|
},
|
|
"file_extension": ".py",
|
|
"mimetype": "text/x-python",
|
|
"name": "python",
|
|
"nbconvert_exporter": "python",
|
|
"pygments_lexer": "ipython3",
|
|
"version": "3.10.5"
|
|
},
|
|
"vscode": {
|
|
"interpreter": {
|
|
"hash": "aee8b7b246df8f9039afb4144a1f6fd8d2ca17a180786b69acc140d282b71a49"
|
|
}
|
|
}
|
|
},
|
|
"nbformat": 4,
|
|
"nbformat_minor": 5
|
|
}
|