mirror of
https://github.com/wassname/peft.git
synced 2026-09-25 13:50:20 +08:00
88 KiB
88 KiB
In [1]:
!pip install transformers accelerate evaluate datasets loralib git+https://github.com/huggingface/peft -qInstalling build dependencies ... [?25l[?25hdone Getting requirements to build wheel ... [?25l[?25hdone Preparing metadata (pyproject.toml) ... [?25l[?25hdone [2K [90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━[0m [32m6.3/6.3 MB[0m [31m55.5 MB/s[0m eta [36m0:00:00[0m [2K [90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━[0m [32m199.7/199.7 KB[0m [31m25.2 MB/s[0m eta [36m0:00:00[0m [2K [90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━[0m [32m81.4/81.4 KB[0m [31m12.3 MB/s[0m eta [36m0:00:00[0m [2K [90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━[0m [32m462.8/462.8 KB[0m [31m41.6 MB/s[0m eta [36m0:00:00[0m [2K [90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━[0m [32m7.6/7.6 MB[0m [31m105.3 MB/s[0m eta [36m0:00:00[0m [2K [90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━[0m [32m190.3/190.3 KB[0m [31m23.9 MB/s[0m eta [36m0:00:00[0m [2K [90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━[0m [32m213.0/213.0 KB[0m [31m27.8 MB/s[0m eta [36m0:00:00[0m [2K [90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━[0m [32m132.0/132.0 KB[0m [31m17.8 MB/s[0m eta [36m0:00:00[0m [2K [90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━[0m [32m76.3/76.3 MB[0m [31m22.0 MB/s[0m eta [36m0:00:00[0m [2K [90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━[0m [32m140.6/140.6 KB[0m [31m19.0 MB/s[0m eta [36m0:00:00[0m [?25h Building wheel for peft (pyproject.toml) ... [?25l[?25hdone
In [ ]:
from huggingface_hub import notebook_login
notebook_login()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
In [3]:
model_checkpoint = (
"google/vit-base-patch16-224-in21k" # pre-trained model from which to fine-tune
)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)
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'
In [6]:
from transformers import AutoImageProcessor
image_processor = AutoImageProcessor.from_pretrained(model_checkpoint)
image_processorOut [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
}
}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_batchIn [8]:
# split up training into training + validation
splits = dataset.train_test_split(test_size=0.1)
train_ds = splits["train"]
val_ds = splits["test"]In [9]:
train_ds.set_transform(preprocess_train)
val_ds.set_transform(preprocess_val)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}"
)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
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
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"],
)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)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}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 [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}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_vittotal 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)[0;31m---------------------------------------------------------------------------[0m
[0;31mHFValidationError[0m Traceback (most recent call last)
[0;32m/usr/local/lib/python3.8/dist-packages/peft/utils/config.py[0m in [0;36mfrom_pretrained[0;34m(cls, pretrained_model_name_or_path, **kwargs)[0m
[1;32m 99[0m [0;32mtry[0m[0;34m:[0m[0;34m[0m[0;34m[0m[0m
[0;32m--> 100[0;31m [0mconfig_file[0m [0;34m=[0m [0mhf_hub_download[0m[0;34m([0m[0mpretrained_model_name_or_path[0m[0;34m,[0m [0mCONFIG_NAME[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m
[0m[1;32m 101[0m [0;32mexcept[0m[0;34m:[0m[0;34m[0m[0;34m[0m[0m
[0;32m/usr/local/lib/python3.8/dist-packages/huggingface_hub/utils/_validators.py[0m in [0;36m_inner_fn[0;34m(*args, **kwargs)[0m
[1;32m 113[0m [0;32mif[0m [0marg_name[0m [0;34m==[0m [0;34m"repo_id"[0m[0;34m:[0m[0;34m[0m[0;34m[0m[0m
[0;32m--> 114[0;31m [0mvalidate_repo_id[0m[0;34m([0m[0marg_value[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m
[0m[1;32m 115[0m [0;34m[0m[0m
[0;32m/usr/local/lib/python3.8/dist-packages/huggingface_hub/utils/_validators.py[0m in [0;36mvalidate_repo_id[0;34m(repo_id)[0m
[1;32m 171[0m [0;32mif[0m [0;32mnot[0m [0mREPO_ID_REGEX[0m[0;34m.[0m[0mmatch[0m[0;34m([0m[0mrepo_id[0m[0;34m)[0m[0;34m:[0m[0;34m[0m[0;34m[0m[0m
[0;32m--> 172[0;31m raise HFValidationError(
[0m[1;32m 173[0m [0;34m"Repo id must use alphanumeric chars or '-', '_', '.', '--' and '..' are"[0m[0;34m[0m[0;34m[0m[0m
[0;31mHFValidationError[0m: 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:
[0;31mValueError[0m Traceback (most recent call last)
[0;32m<ipython-input-21-7757a41e7038>[0m in [0;36m<module>[0;34m[0m
[1;32m 2[0m [0;34m[0m[0m
[1;32m 3[0m [0;34m[0m[0m
[0;32m----> 4[0;31m [0mconfig[0m [0;34m=[0m [0mPeftConfig[0m[0;34m.[0m[0mfrom_pretrained[0m[0;34m([0m[0mpeft_model_id[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m
[0m[1;32m 5[0m model = AutoModelForImageClassification.from_pretrained(
[1;32m 6[0m [0mconfig[0m[0;34m.[0m[0mbase_model_name_or_path[0m[0;34m,[0m[0;34m[0m[0;34m[0m[0m
[0;32m/usr/local/lib/python3.8/dist-packages/peft/utils/config.py[0m in [0;36mfrom_pretrained[0;34m(cls, pretrained_model_name_or_path, **kwargs)[0m
[1;32m 100[0m [0mconfig_file[0m [0;34m=[0m [0mhf_hub_download[0m[0;34m([0m[0mpretrained_model_name_or_path[0m[0;34m,[0m [0mCONFIG_NAME[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m
[1;32m 101[0m [0;32mexcept[0m[0;34m:[0m[0;34m[0m[0;34m[0m[0m
[0;32m--> 102[0;31m [0;32mraise[0m [0mValueError[0m[0;34m([0m[0;34mf"Can't find config.json at '{pretrained_model_name_or_path}'"[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m
[0m[1;32m 103[0m [0;34m[0m[0m
[1;32m 104[0m [0mloaded_attributes[0m [0;34m=[0m [0mcls[0m[0;34m.[0m[0mfrom_json_file[0m[0;34m([0m[0mconfig_file[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m
[0;31mValueError[0m: Can't find config.json at './temp_lora_vit'