Files

31 KiB

In [1]:
import argparse
import os

import torch
from torch.optim import AdamW
from torch.utils.data import DataLoader
from peft import (
    get_peft_config,
    get_peft_model,
    get_peft_model_state_dict,
    set_peft_model_state_dict,
    PeftType,
    PrefixTuningConfig,
    PromptEncoderConfig,
)

import evaluate
from datasets import load_dataset
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
from tqdm import tqdm
===================================BUG REPORT===================================
Welcome to bitsandbytes. For bug reports, please submit your error trace to: https://github.com/TimDettmers/bitsandbytes/issues
For effortless bug reporting copy-paste your error into this form: https://docs.google.com/forms/d/e/1FAIpQLScPB8emS3Thkp66nvqwmjTEgxp8Y9ufuWTzFyr9kJ5AoI47dQ/viewform?usp=sf_link
================================================================================
CUDA SETUP: CUDA runtime path found: /home/sourab/miniconda3/envs/ml/lib/libcudart.so
CUDA SETUP: Highest compute capability among GPUs detected: 7.5
CUDA SETUP: Detected CUDA version 117
CUDA SETUP: Loading binary /home/sourab/miniconda3/envs/ml/lib/python3.10/site-packages/bitsandbytes/libbitsandbytes_cuda117.so...
In [2]:
batch_size = 32
model_name_or_path = "roberta-large"
task = "mrpc"
peft_type = PeftType.P_TUNING
device = "cuda"
num_epochs = 20
In [3]:
peft_config = PromptEncoderConfig(task_type="SEQ_CLS", num_virtual_tokens=20, encoder_hidden_size=128)
lr = 1e-3
In [4]:
if any(k in model_name_or_path for k in ("gpt", "opt", "bloom")):
    padding_side = "left"
else:
    padding_side = "right"

tokenizer = AutoTokenizer.from_pretrained(model_name_or_path, padding_side=padding_side)
if getattr(tokenizer, "pad_token_id") is None:
    tokenizer.pad_token_id = tokenizer.eos_token_id

datasets = load_dataset("glue", task)
metric = evaluate.load("glue", task)


def tokenize_function(examples):
    # max_length=None => use the model max length (it's actually the default)
    outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
    return outputs


tokenized_datasets = datasets.map(
    tokenize_function,
    batched=True,
    remove_columns=["idx", "sentence1", "sentence2"],
)

# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
# transformers library
tokenized_datasets = tokenized_datasets.rename_column("label", "labels")


def collate_fn(examples):
    return tokenizer.pad(examples, padding="longest", return_tensors="pt")


# Instantiate dataloaders.
train_dataloader = DataLoader(tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size)
eval_dataloader = DataLoader(
    tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=batch_size
)
Found cached dataset glue (/home/sourab/.cache/huggingface/datasets/glue/mrpc/1.0.0/dacbe3125aa31d7f70367a07a8a9e72a5a0bfeb5fc42e75c9db75b96da6053ad)
  0%|          | 0/3 [00:00<?, ?it/s]
Loading cached processed dataset at /home/sourab/.cache/huggingface/datasets/glue/mrpc/1.0.0/dacbe3125aa31d7f70367a07a8a9e72a5a0bfeb5fc42e75c9db75b96da6053ad/cache-9fa7887f9eaa03ae.arrow
Loading cached processed dataset at /home/sourab/.cache/huggingface/datasets/glue/mrpc/1.0.0/dacbe3125aa31d7f70367a07a8a9e72a5a0bfeb5fc42e75c9db75b96da6053ad/cache-dc593149bbeafe80.arrow
Loading cached processed dataset at /home/sourab/.cache/huggingface/datasets/glue/mrpc/1.0.0/dacbe3125aa31d7f70367a07a8a9e72a5a0bfeb5fc42e75c9db75b96da6053ad/cache-140ebe5b70e09817.arrow
In [ ]:
model = AutoModelForSequenceClassification.from_pretrained(model_name_or_path, return_dict=True)
model = get_peft_model(model, peft_config)
model.print_trainable_parameters()
model
In [6]:
optimizer = AdamW(params=model.parameters(), lr=lr)

# Instantiate scheduler
lr_scheduler = get_linear_schedule_with_warmup(
    optimizer=optimizer,
    num_warmup_steps=0,  # 0.06*(len(train_dataloader) * num_epochs),
    num_training_steps=(len(train_dataloader) * num_epochs),
)
In [7]:
model.to(device)
for epoch in range(num_epochs):
    model.train()
    for step, batch in enumerate(tqdm(train_dataloader)):
        batch.to(device)
        outputs = model(**batch)
        loss = outputs.loss
        loss.backward()
        optimizer.step()
        lr_scheduler.step()
        optimizer.zero_grad()

    model.eval()
    for step, batch in enumerate(tqdm(eval_dataloader)):
        batch.to(device)
        with torch.no_grad():
            outputs = model(**batch)
        predictions = outputs.logits.argmax(dim=-1)
        predictions, references = predictions, batch["labels"]
        metric.add_batch(
            predictions=predictions,
            references=references,
        )

    eval_metric = metric.compute()
    print(f"epoch {epoch}:", eval_metric)
  0%|                                                                                                  | 0/115 [00:00<?, ?it/s]You're using a RobertaTokenizerFast tokenizer. Please note that with a fast tokenizer, using the `__call__` method is faster than using a method to encode the text followed by a call to the `pad` method to get a padded encoding.
100%|████████████████████████████████████████████████████████████████████████████████████████| 115/115 [00:32<00:00,  3.54it/s]
100%|██████████████████████████████████████████████████████████████████████████████████████████| 13/13 [00:01<00:00,  6.91it/s]
epoch 0: {'accuracy': 0.6985294117647058, 'f1': 0.8172362555720655}
100%|████████████████████████████████████████████████████████████████████████████████████████| 115/115 [00:31<00:00,  3.61it/s]
100%|██████████████████████████████████████████████████████████████████████████████████████████| 13/13 [00:01<00:00,  6.87it/s]
epoch 1: {'accuracy': 0.6936274509803921, 'f1': 0.806201550387597}
100%|████████████████████████████████████████████████████████████████████████████████████████| 115/115 [00:31<00:00,  3.61it/s]
100%|██████████████████████████████████████████████████████████████████████████████████████████| 13/13 [00:01<00:00,  6.88it/s]
epoch 2: {'accuracy': 0.7132352941176471, 'f1': 0.8224582701062216}
100%|████████████████████████████████████████████████████████████████████████████████████████| 115/115 [00:31<00:00,  3.61it/s]
100%|██████████████████████████████████████████████████████████████████████████████████████████| 13/13 [00:01<00:00,  6.87it/s]
epoch 3: {'accuracy': 0.7083333333333334, 'f1': 0.8199697428139183}
100%|████████████████████████████████████████████████████████████████████████████████████████| 115/115 [00:31<00:00,  3.61it/s]
100%|██████████████████████████████████████████████████████████████████████████████████████████| 13/13 [00:01<00:00,  6.90it/s]
epoch 4: {'accuracy': 0.7205882352941176, 'f1': 0.8246153846153846}
100%|████████████████████████████████████████████████████████████████████████████████████████| 115/115 [00:31<00:00,  3.62it/s]
100%|██████████████████████████████████████████████████████████████████████████████████████████| 13/13 [00:01<00:00,  6.90it/s]
epoch 5: {'accuracy': 0.7009803921568627, 'f1': 0.8200589970501474}
100%|████████████████████████████████████████████████████████████████████████████████████████| 115/115 [00:32<00:00,  3.59it/s]
100%|██████████████████████████████████████████████████████████████████████████████████████████| 13/13 [00:01<00:00,  6.89it/s]
epoch 6: {'accuracy': 0.7254901960784313, 'f1': 0.8292682926829268}
100%|████████████████████████████████████████████████████████████████████████████████████████| 115/115 [00:31<00:00,  3.60it/s]
100%|██████████████████████████████████████████████████████████████████████████████████████████| 13/13 [00:01<00:00,  6.86it/s]
epoch 7: {'accuracy': 0.7230392156862745, 'f1': 0.8269525267993874}
100%|████████████████████████████████████████████████████████████████████████████████████████| 115/115 [00:34<00:00,  3.34it/s]
100%|██████████████████████████████████████████████████████████████████████████████████████████| 13/13 [00:01<00:00,  6.88it/s]
epoch 8: {'accuracy': 0.7254901960784313, 'f1': 0.8297872340425533}
100%|████████████████████████████████████████████████████████████████████████████████████████| 115/115 [00:31<00:00,  3.60it/s]
100%|██████████████████████████████████████████████████████████████████████████████████████████| 13/13 [00:01<00:00,  6.77it/s]
epoch 9: {'accuracy': 0.7230392156862745, 'f1': 0.828006088280061}
100%|████████████████████████████████████████████████████████████████████████████████████████| 115/115 [00:32<00:00,  3.58it/s]
100%|██████████████████████████████████████████████████████████████████████████████████████████| 13/13 [00:01<00:00,  6.88it/s]
epoch 10: {'accuracy': 0.7181372549019608, 'f1': 0.8183254344391785}
100%|████████████████████████████████████████████████████████████████████████████████████████| 115/115 [00:31<00:00,  3.60it/s]
100%|██████████████████████████████████████████████████████████████████████████████████████████| 13/13 [00:01<00:00,  6.87it/s]
epoch 11: {'accuracy': 0.7132352941176471, 'f1': 0.803361344537815}
100%|████████████████████████████████████████████████████████████████████████████████████████| 115/115 [00:31<00:00,  3.59it/s]
100%|██████████████████████████████████████████████████████████████████████████████████████████| 13/13 [00:01<00:00,  6.85it/s]
epoch 12: {'accuracy': 0.7107843137254902, 'f1': 0.8206686930091186}
100%|████████████████████████████████████████████████████████████████████████████████████████| 115/115 [00:32<00:00,  3.59it/s]
100%|██████████████████████████████████████████████████████████████████████████████████████████| 13/13 [00:01<00:00,  6.85it/s]
epoch 13: {'accuracy': 0.7181372549019608, 'f1': 0.8254931714719272}
100%|████████████████████████████████████████████████████████████████████████████████████████| 115/115 [00:32<00:00,  3.59it/s]
100%|██████████████████████████████████████████████████████████████████████████████████████████| 13/13 [00:01<00:00,  6.87it/s]
epoch 14: {'accuracy': 0.7156862745098039, 'f1': 0.8253012048192772}
100%|████████████████████████████████████████████████████████████████████████████████████████| 115/115 [00:32<00:00,  3.59it/s]
100%|██████████████████████████████████████████████████████████████████████████████████████████| 13/13 [00:01<00:00,  6.84it/s]
epoch 15: {'accuracy': 0.7230392156862745, 'f1': 0.8242612752721618}
100%|████████████████████████████████████████████████████████████████████████████████████████| 115/115 [00:32<00:00,  3.49it/s]
100%|██████████████████████████████████████████████████████████████████████████████████████████| 13/13 [00:02<00:00,  5.84it/s]
epoch 16: {'accuracy': 0.7181372549019608, 'f1': 0.8200312989045383}
100%|████████████████████████████████████████████████████████████████████████████████████████| 115/115 [00:32<00:00,  3.49it/s]
100%|██████████████████████████████████████████████████████████████████████████████████████████| 13/13 [00:01<00:00,  6.84it/s]
epoch 17: {'accuracy': 0.7107843137254902, 'f1': 0.8217522658610272}
100%|████████████████████████████████████████████████████████████████████████████████████████| 115/115 [00:31<00:00,  3.60it/s]
100%|██████████████████████████████████████████████████████████████████████████████████████████| 13/13 [00:01<00:00,  6.88it/s]
epoch 18: {'accuracy': 0.7254901960784313, 'f1': 0.8292682926829268}
100%|████████████████████████████████████████████████████████████████████████████████████████| 115/115 [00:31<00:00,  3.61it/s]
100%|██████████████████████████████████████████████████████████████████████████████████████████| 13/13 [00:01<00:00,  6.89it/s]
epoch 19: {'accuracy': 0.7107843137254902, 'f1': 0.8206686930091186}

Share adapters on the 🤗 Hub

In [8]:
model.push_to_hub("smangrul/roberta-large-peft-p-tuning", use_auth_token=True)
Out [8]:
CommitInfo(commit_url='https://huggingface.co/smangrul/roberta-large-peft-p-tuning/commit/fa7abe613f498c76df5e16c85d9c19c3019587a7', commit_message='Upload model', commit_description='', oid='fa7abe613f498c76df5e16c85d9c19c3019587a7', pr_url=None, pr_revision=None, pr_num=None)

Load adapters from the Hub

You can also directly load adapters from the Hub using the commands below:

In [9]:
import torch
from peft import PeftModel, PeftConfig
from transformers import AutoModelForCausalLM, AutoTokenizer

peft_model_id = "smangrul/roberta-large-peft-p-tuning"
config = PeftConfig.from_pretrained(peft_model_id)
inference_model = AutoModelForSequenceClassification.from_pretrained(config.base_model_name_or_path)
tokenizer = AutoTokenizer.from_pretrained(config.base_model_name_or_path)

# Load the Lora model
inference_model = PeftModel.from_pretrained(inference_model, peft_model_id)

inference_model.to(device)
inference_model.eval()
for step, batch in enumerate(tqdm(eval_dataloader)):
    batch.to(device)
    with torch.no_grad():
        outputs = inference_model(**batch)
    predictions = outputs.logits.argmax(dim=-1)
    predictions, references = predictions, batch["labels"]
    metric.add_batch(
        predictions=predictions,
        references=references,
    )

eval_metric = metric.compute()
print(eval_metric)
Some weights of the model checkpoint at roberta-large were not used when initializing RobertaForSequenceClassification: ['lm_head.decoder.weight', 'lm_head.layer_norm.bias', 'lm_head.dense.bias', 'roberta.pooler.dense.weight', 'lm_head.layer_norm.weight', 'roberta.pooler.dense.bias', 'lm_head.dense.weight', 'lm_head.bias']
- This IS expected if you are initializing RobertaForSequenceClassification from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).
- This IS NOT expected if you are initializing RobertaForSequenceClassification from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).
Some weights of RobertaForSequenceClassification were not initialized from the model checkpoint at roberta-large and are newly initialized: ['classifier.dense.weight', 'classifier.dense.bias', 'classifier.out_proj.weight', 'classifier.out_proj.bias']
You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.
Downloading:   0%|          | 0.00/4.29M [00:00<?, ?B/s]
  0%|                                                                                                   | 0/13 [00:00<?, ?it/s]You're using a RobertaTokenizerFast tokenizer. Please note that with a fast tokenizer, using the `__call__` method is faster than using a method to encode the text followed by a call to the `pad` method to get a padded encoding.
100%|██████████████████████████████████████████████████████████████████████████████████████████| 13/13 [00:01<00:00,  7.18it/s]
{'accuracy': 0.7107843137254902, 'f1': 0.8206686930091186}
In [ ]: