Files
peft/examples/image_classification/image_classification_peft_lora.ipynb
T

88 KiB

Introduction

In this notebook, we will learn how to use LoRA from 🤗 PEFT to fine-tune an image classification modelby ONLY using 0.6% of the original trainable parameters of the model.

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.

Let's get started by installing the dependencies.

Install dependencies

Here we're installing peft from source to ensure we have access to all the bleeding edge features of peft.

In [1]:
!pip install transformers accelerate evaluate datasets loralib git+https://github.com/huggingface/peft -q
  Installing build dependencies ... [?25l[?25hdone
  Getting requirements to build wheel ... [?25l[?25hdone
  Preparing metadata (pyproject.toml) ... [?25l[?25hdone
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 6.3/6.3 MB 55.5 MB/s eta 0:00:00
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 199.7/199.7 KB 25.2 MB/s eta 0:00:00
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 81.4/81.4 KB 12.3 MB/s eta 0:00:00
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 462.8/462.8 KB 41.6 MB/s eta 0:00:00
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 7.6/7.6 MB 105.3 MB/s eta 0:00:00
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 190.3/190.3 KB 23.9 MB/s eta 0:00:00
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 213.0/213.0 KB 27.8 MB/s eta 0:00:00
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 132.0/132.0 KB 17.8 MB/s eta 0:00:00
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 76.3/76.3 MB 22.0 MB/s eta 0:00:00
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 140.6/140.6 KB 19.0 MB/s eta 0:00:00
[?25h  Building wheel for peft (pyproject.toml) ... [?25l[?25hdone

Authentication

We will share our fine-tuned model at the end of training. So, to do that we just authenticate using our 🤗 token. This token is available from here. If you don't have a 🤗 account already, we highly encourage you to do so; it's free!

In [ ]:
from huggingface_hub import notebook_login

notebook_login()

Check the library versions

In [1]:
import transformers 
import accelerate
import peft
===================================BUG REPORT===================================
Welcome to bitsandbytes. For bug reports, please submit your error trace to: https://github.com/TimDettmers/bitsandbytes/issues
================================================================================
In [2]:
print(f"Transformers version: {transformers.__version__}")
print(f"Accelerate version: {accelerate.__version__}")
print(f"PEFT version: {peft.__version__}")
Transformers version: 4.26.0
Accelerate version: 0.16.0
PEFT version: 0.1.0.dev0

Select a model checkpoint to fine-tune

In [3]:
model_checkpoint = (
    "google/vit-base-patch16-224-in21k"  # pre-trained model from which to fine-tune
)

Load a dataset

We're only loading the first 5000 instances from the training set of the Food-101 dataset to keep this example runtime short.

In [4]:
from datasets import load_dataset

dataset = load_dataset("food101", split="train[:5000]")
WARNING:datasets.builder:Found cached dataset food101 (/root/.cache/huggingface/datasets/food101/default/0.0.0/7cebe41a80fb2da3f08fcbef769c8874073a86346f7fb96dc0847d4dfc318295)

Prepare datasets for training and evaluation

  1. Prepare label2id and id2label dictionaries. This will come in handy when performing inference and for metadata information.
In [5]:
labels = dataset.features["label"].names
label2id, id2label = dict(), dict()
for i, label in enumerate(labels):
    label2id[label] = i
    id2label[i] = label

id2label[2]
Out [5]:
'baklava'
  1. We load the image processor of the model we're fine-tuning.
In [6]:
from transformers import AutoImageProcessor

image_processor = AutoImageProcessor.from_pretrained(model_checkpoint)
image_processor
Out [6]:
ViTImageProcessor {
  "do_normalize": true,
  "do_rescale": true,
  "do_resize": true,
  "image_mean": [
    0.5,
    0.5,
    0.5
  ],
  "image_processor_type": "ViTImageProcessor",
  "image_std": [
    0.5,
    0.5,
    0.5
  ],
  "resample": 2,
  "rescale_factor": 0.00392156862745098,
  "size": {
    "height": 224,
    "width": 224
  }
}

As one might notice, the image_processor has useful information on which size the training and evaluation images should be resized, stats that should be used to normalize the pixel values, etc.

  1. Using the image processor we prepare transformation functions for the datasets. These functions will include augmentation and pixel scaling.
In [7]:
from torchvision.transforms import (
    CenterCrop,
    Compose,
    Normalize,
    RandomHorizontalFlip,
    RandomResizedCrop,
    Resize,
    ToTensor,
)

normalize = Normalize(mean=image_processor.image_mean, std=image_processor.image_std)
train_transforms = Compose(
    [
        RandomResizedCrop(image_processor.size["height"]),
        RandomHorizontalFlip(),
        ToTensor(),
        normalize,
    ]
)

val_transforms = Compose(
    [
        Resize(image_processor.size["height"]),
        CenterCrop(image_processor.size["height"]),
        ToTensor(),
        normalize,
    ]
)


def preprocess_train(example_batch):
    """Apply train_transforms across a batch."""
    example_batch["pixel_values"] = [
        train_transforms(image.convert("RGB")) for image in example_batch["image"]
    ]
    return example_batch


def preprocess_val(example_batch):
    """Apply val_transforms across a batch."""
    example_batch["pixel_values"] = [
        val_transforms(image.convert("RGB")) for image in example_batch["image"]
    ]
    return example_batch
  1. We split our mini dataset into training and validation.
In [8]:
# split up training into training + validation
splits = dataset.train_test_split(test_size=0.1)
train_ds = splits["train"]
val_ds = splits["test"]
  1. We set the transformation functions to the datasets accordingly.
In [9]:
train_ds.set_transform(preprocess_train)
val_ds.set_transform(preprocess_val)

Load and prepare a model

In this section, we first load the model we want to fine-tune.

In [10]:
def print_trainable_parameters(model):
    """
    Prints the number of trainable parameters in the model.
    """
    trainable_params = 0
    all_param = 0
    for _, param in model.named_parameters():
        all_param += param.numel()
        if param.requires_grad:
            trainable_params += param.numel()
    print(
        f"trainable params: {trainable_params} || all params: {all_param} || trainable%: {100 * trainable_params / all_param:.2f}"
    )

The LoraModel class that we will use in a moment is wrapper of the original model to be fine-tuned. So, it's important for us to initialize the original model correctly. As such, we initialize it by specifying the label2id and id2label so that AutoModelForImageClassification can initialize a append classification head to the underlying model, adapted for our dataset. We can confirm this from the warning below:

Some weights of ViTForImageClassification were not initialized from the model checkpoint at google/vit-base-patch16-224-in21k and are newly initialized: ['classifier.weight', 'classifier.bias']
In [11]:
from transformers import AutoModelForImageClassification, TrainingArguments, Trainer

model = AutoModelForImageClassification.from_pretrained(
    model_checkpoint,
    label2id=label2id,
    id2label=id2label,
    ignore_mismatched_sizes=True,  # provide this in case you're planning to fine-tune an already fine-tuned checkpoint
)
print_trainable_parameters(model)
Some weights of the model checkpoint at google/vit-base-patch16-224-in21k were not used when initializing ViTForImageClassification: ['pooler.dense.bias', 'pooler.dense.weight']
- This IS expected if you are initializing ViTForImageClassification 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 ViTForImageClassification from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).
Some weights of ViTForImageClassification were not initialized from the model checkpoint at google/vit-base-patch16-224-in21k and are newly initialized: ['classifier.weight', 'classifier.bias']
You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.
trainable params: 85876325 || all params: 85876325 || trainable%: 100.00

Also, take note of the number of total trainable parameters of model: it's 100%! We'll compare this number to that of the LoRA model.

We now use the LoraModel to wrap model so that the "update" matrices are added to the respective places.

In [12]:
from peft import LoraConfig, LoraModel

config = LoraConfig(
    r=16,
    lora_alpha=16,
    target_modules=["query", "value"],
    lora_dropout=0.1,
    bias="none",
    modules_to_save=["classifier"],
)
lora_model = LoraModel(config, model)
print_trainable_parameters(lora_model)
trainable params: 589824 || all params: 86466149 || trainable%: 0.68

Let's unpack what's going on here.

In order for LoRA to take effect, we need to specify the target modules to LoraConfig so that LoraModel knows which modules inside our model needs to be amended with LoRA matrices. In this case, we're only interested in targetting the query and value matrices of the attention blocks of the base model. Since the parameters corresponding to these matrices are "named" with query and value respectively, we specify them accordingly in the target_modules argument of LoraConfig.

We also specify modules_to_save. After we wrap our base model model with LoraModel along with the config, we get a new model where only the LoRA parameters are trainable (so-called "update matrices") while the pre-trained parameters are kept frozen. These include the parameters of the randomly initialized classifier parameters too. This is NOT we want when fine-tuning the base model on our custom dataset. To ensure that the classifier parameters are also trained, we specify modules_to_save. This also ensures that these modules are serialized alongside the LoRA trainable parameters when using utilities like save_pretrained() and push_to_hub().

Regarding the other parameters:

  • r: The dimension used by the LoRA update matrices.
  • alpha: Scaling factor.
  • bias: Specifying if the bias parameters should be trained. None denotes none of the bias parameters will be trained.

r and alpha together control the total number of final trainable parameters when using LoRA giving us the flexbility to balance a trade-off between end performance and compute efficiency.

We can also how many parameters we're actually training. Since we're interested in performing parameter-efficient fine-tuning, we should expect to notice a less number of trainable parameters from the lora_model in comparison to the original model which is indeed the case here.

Training arguments

We will leverage 🤗 Trainer for fine-tuning. It accepts several arguments which we wrap using TrainingArguments.

In [13]:
from transformers import TrainingArguments, Trainer


model_name = model_checkpoint.split("/")[-1]
batch_size = 128

args = TrainingArguments(
    f"{model_name}-finetuned-lora-food101",
    remove_unused_columns=False,
    evaluation_strategy="epoch",
    save_strategy="epoch",
    learning_rate=5e-3,
    per_device_train_batch_size=batch_size,
    gradient_accumulation_steps=4,
    per_device_eval_batch_size=batch_size,
    fp16=True,
    num_train_epochs=5,
    logging_steps=10,
    load_best_model_at_end=True,
    metric_for_best_model="accuracy",
    push_to_hub=True,
    label_names=["labels"],
)

Some things to note here:

  • We're using a larger batch size since there is only a handful of parameters to train.
  • Larger learning rate than the normal (1e-5 for example).

All of these things are a byproduct of the fact that we're training only a small number of parameters. This can potentially also reduce the need to conduct expensive hyperparameter tuning experiments.

Prepare evaluation metric

In [14]:
import numpy as np
import evaluate


metric = evaluate.load("accuracy")

# the compute_metrics function takes a Named Tuple as input:
# predictions, which are the logits of the model as Numpy arrays,
# and label_ids, which are the ground-truth labels as Numpy arrays.
def compute_metrics(eval_pred):
    """Computes accuracy on a batch of predictions"""
    predictions = np.argmax(eval_pred.predictions, axis=1)
    return metric.compute(predictions=predictions, references=eval_pred.label_ids)

Collation function

This is used by Trainer to gather a batch of training and evaluation examples and prepare them in a format that is acceptable by the underlying model.

In [15]:
import torch


def collate_fn(examples):
    pixel_values = torch.stack([example["pixel_values"] for example in examples])
    labels = torch.tensor([example["label"] for example in examples])
    return {"pixel_values": pixel_values, "labels": labels}

Train and evaluate

In [16]:
trainer = Trainer(
    model,
    args,
    train_dataset=train_ds,
    eval_dataset=val_ds,
    tokenizer=image_processor,
    compute_metrics=compute_metrics,
    data_collator=collate_fn,
)
train_results = trainer.train()
/content/vit-base-patch16-224-in21k-finetuned-lora-food101 is already a clone of https://huggingface.co/sayakpaul/vit-base-patch16-224-in21k-finetuned-lora-food101. Make sure you pull the latest changes with `repo.git_pull()`.
WARNING:huggingface_hub.repository:/content/vit-base-patch16-224-in21k-finetuned-lora-food101 is already a clone of https://huggingface.co/sayakpaul/vit-base-patch16-224-in21k-finetuned-lora-food101. Make sure you pull the latest changes with `repo.git_pull()`.
Clean file pytorch_model.bin:   0%|          | 1.00k/329M [00:00<?, ?B/s]
Using cuda_amp half precision backend
/usr/local/lib/python3.8/dist-packages/transformers/optimization.py:306: FutureWarning: This implementation of AdamW is deprecated and will be removed in a future version. Use the PyTorch implementation torch.optim.AdamW instead, or set `no_deprecation_warning=True` to disable this warning
  warnings.warn(
***** Running training *****
  Num examples = 4500
  Num Epochs = 5
  Instantaneous batch size per device = 128
  Total train batch size (w. parallel, distributed & accumulation) = 512
  Gradient Accumulation steps = 4
  Total optimization steps = 45
  Number of trainable parameters = 589824
[45/45 03:58, Epoch 5/5]
Epoch Training Loss Validation Loss Accuracy
1 No log 3.565926 0.414000
2 4.064000 3.101344 0.642000
3 3.318700 2.758389 0.794000
4 2.895100 2.536666 0.836000
5 2.614700 2.453719 0.842000

***** Running Evaluation *****
  Num examples = 500
  Batch size = 128
Saving model checkpoint to vit-base-patch16-224-in21k-finetuned-lora-food101/checkpoint-9
Configuration saved in vit-base-patch16-224-in21k-finetuned-lora-food101/checkpoint-9/config.json
Model weights saved in vit-base-patch16-224-in21k-finetuned-lora-food101/checkpoint-9/pytorch_model.bin
Image processor saved in vit-base-patch16-224-in21k-finetuned-lora-food101/checkpoint-9/preprocessor_config.json
Image processor saved in vit-base-patch16-224-in21k-finetuned-lora-food101/preprocessor_config.json
***** Running Evaluation *****
  Num examples = 500
  Batch size = 128
Saving model checkpoint to vit-base-patch16-224-in21k-finetuned-lora-food101/checkpoint-18
Configuration saved in vit-base-patch16-224-in21k-finetuned-lora-food101/checkpoint-18/config.json
Model weights saved in vit-base-patch16-224-in21k-finetuned-lora-food101/checkpoint-18/pytorch_model.bin
Image processor saved in vit-base-patch16-224-in21k-finetuned-lora-food101/checkpoint-18/preprocessor_config.json
***** Running Evaluation *****
  Num examples = 500
  Batch size = 128
Saving model checkpoint to vit-base-patch16-224-in21k-finetuned-lora-food101/checkpoint-27
Configuration saved in vit-base-patch16-224-in21k-finetuned-lora-food101/checkpoint-27/config.json
Model weights saved in vit-base-patch16-224-in21k-finetuned-lora-food101/checkpoint-27/pytorch_model.bin
Image processor saved in vit-base-patch16-224-in21k-finetuned-lora-food101/checkpoint-27/preprocessor_config.json
Image processor saved in vit-base-patch16-224-in21k-finetuned-lora-food101/preprocessor_config.json
***** Running Evaluation *****
  Num examples = 500
  Batch size = 128
Saving model checkpoint to vit-base-patch16-224-in21k-finetuned-lora-food101/checkpoint-36
Configuration saved in vit-base-patch16-224-in21k-finetuned-lora-food101/checkpoint-36/config.json
Model weights saved in vit-base-patch16-224-in21k-finetuned-lora-food101/checkpoint-36/pytorch_model.bin
Image processor saved in vit-base-patch16-224-in21k-finetuned-lora-food101/checkpoint-36/preprocessor_config.json
***** Running Evaluation *****
  Num examples = 500
  Batch size = 128
Saving model checkpoint to vit-base-patch16-224-in21k-finetuned-lora-food101/checkpoint-45
Configuration saved in vit-base-patch16-224-in21k-finetuned-lora-food101/checkpoint-45/config.json
Model weights saved in vit-base-patch16-224-in21k-finetuned-lora-food101/checkpoint-45/pytorch_model.bin
Image processor saved in vit-base-patch16-224-in21k-finetuned-lora-food101/checkpoint-45/preprocessor_config.json
Image processor saved in vit-base-patch16-224-in21k-finetuned-lora-food101/preprocessor_config.json


Training completed. Do not forget to share your model on huggingface.co/models =)


Loading best model from vit-base-patch16-224-in21k-finetuned-lora-food101/checkpoint-45 (score: 0.842).

In just a few minutes, we have a fine-tuned model with 84.2% validation accuracy. Also, note that we used a very small subset of the training dataset which is definitely impacting the results.

In [17]:
trainer.evaluate(val_ds)
Out [17]:
***** Running Evaluation *****
  Num examples = 500
  Batch size = 128
[4/4 00:02]
{'eval_loss': 2.453718662261963,
 'eval_accuracy': 0.842,
 'eval_runtime': 3.7766,
 'eval_samples_per_second': 132.395,
 'eval_steps_per_second': 1.059,
 'epoch': 5.0}

Sharing your model and inference

[TODO]

In [19]:
trainer.push_to_hub()
Out [19]:
Saving model checkpoint to vit-base-patch16-224-in21k-finetuned-lora-food101
Configuration saved in vit-base-patch16-224-in21k-finetuned-lora-food101/config.json
Model weights saved in vit-base-patch16-224-in21k-finetuned-lora-food101/pytorch_model.bin
Image processor saved in vit-base-patch16-224-in21k-finetuned-lora-food101/preprocessor_config.json
Several commits (2) will be pushed upstream.
WARNING:huggingface_hub.repository:Several commits (2) will be pushed upstream.
The progress bars may be unreliable.
WARNING:huggingface_hub.repository:The progress bars may be unreliable.
Upload file pytorch_model.bin:   0%|          | 32.0k/329M [00:00<?, ?B/s]
Upload file runs/Feb07_02-50-30_319afa680fd7/events.out.tfevents.1675738403.319afa680fd7.10047.2: 100%|#######…
Upload file runs/Feb07_02-50-30_319afa680fd7/events.out.tfevents.1675738246.319afa680fd7.10047.0: 100%|#######…
remote: Scanning LFS files for validity...        
remote: LFS file scan complete.        
To https://huggingface.co/sayakpaul/vit-base-patch16-224-in21k-finetuned-lora-food101
   e877e50..4ada42e  main -> main

WARNING:huggingface_hub.repository:remote: Scanning LFS files for validity...        
remote: LFS file scan complete.        
To https://huggingface.co/sayakpaul/vit-base-patch16-224-in21k-finetuned-lora-food101
   e877e50..4ada42e  main -> main

To https://huggingface.co/sayakpaul/vit-base-patch16-224-in21k-finetuned-lora-food101
   4ada42e..5fdbe0d  main -> main

WARNING:huggingface_hub.repository:To https://huggingface.co/sayakpaul/vit-base-patch16-224-in21k-finetuned-lora-food101
   4ada42e..5fdbe0d  main -> main

'https://huggingface.co/sayakpaul/vit-base-patch16-224-in21k-finetuned-lora-food101/commit/4ada42e122bcb831340bc1deb924cc1d574b3951'
In [20]:
lora_model.push_to_hub("sayakpaul/vit-base-patch16-224-in21k-finetuned-lora-food101")
Out [20]:
Configuration saved in vit-base-patch16-224-in21k-finetuned-lora-food101/config.json
Model weights saved in vit-base-patch16-224-in21k-finetuned-lora-food101/pytorch_model.bin
Uploading the following files to sayakpaul/vit-base-patch16-224-in21k-finetuned-lora-food101: pytorch_model.bin,config.json
CommitInfo(commit_url='https://huggingface.co/sayakpaul/vit-base-patch16-224-in21k-finetuned-lora-food101/commit/430778499b3856a006868c5caa4ea75faa450c2a', commit_message='Upload ViTForImageClassification', commit_description='', oid='430778499b3856a006868c5caa4ea75faa450c2a', pr_url=None, pr_revision=None, pr_num=None)
In [20]:
peft_model_id = "./temp_lora_vit"
lora_model.save_pretrained(peft_model_id)
Configuration saved in ./temp_lora_vit/config.json
Model weights saved in ./temp_lora_vit/pytorch_model.bin
In [22]:
!ls -lh temp_lora_vit
total 330M
-rw-r--r-- 1 root root 5.4K Feb  7 04:04 config.json
-rw-r--r-- 1 root root 330M Feb  7 04:04 pytorch_model.bin
In [21]:
from peft import PeftConfig, PeftModel


config = PeftConfig.from_pretrained(peft_model_id)
model = AutoModelForImageClassification.from_pretrained(
    config.base_model_name_or_path,
)
# Load the Lora model
inference_model = PeftModel.from_pretrained(model, peft_model_id)
---------------------------------------------------------------------------
HFValidationError                         Traceback (most recent call last)
/usr/local/lib/python3.8/dist-packages/peft/utils/config.py in from_pretrained(cls, pretrained_model_name_or_path, **kwargs)
     99             try:
--> 100                 config_file = hf_hub_download(pretrained_model_name_or_path, CONFIG_NAME)
    101             except:

/usr/local/lib/python3.8/dist-packages/huggingface_hub/utils/_validators.py in _inner_fn(*args, **kwargs)
    113             if arg_name == "repo_id":
--> 114                 validate_repo_id(arg_value)
    115 

/usr/local/lib/python3.8/dist-packages/huggingface_hub/utils/_validators.py in validate_repo_id(repo_id)
    171     if not REPO_ID_REGEX.match(repo_id):
--> 172         raise HFValidationError(
    173             "Repo id must use alphanumeric chars or '-', '_', '.', '--' and '..' are"

HFValidationError: Repo id must use alphanumeric chars or '-', '_', '.', '--' and '..' are forbidden, '-' and '.' cannot start or end the name, max length is 96: './temp_lora_vit'.

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-21-7757a41e7038> in <module>
      2 
      3 
----> 4 config = PeftConfig.from_pretrained(peft_model_id)
      5 model = AutoModelForImageClassification.from_pretrained(
      6     config.base_model_name_or_path,

/usr/local/lib/python3.8/dist-packages/peft/utils/config.py in from_pretrained(cls, pretrained_model_name_or_path, **kwargs)
    100                 config_file = hf_hub_download(pretrained_model_name_or_path, CONFIG_NAME)
    101             except:
--> 102                 raise ValueError(f"Can't find config.json at '{pretrained_model_name_or_path}'")
    103 
    104         loaded_attributes = cls.from_json_file(config_file)

ValueError: Can't find config.json at './temp_lora_vit'