Views
No views yet
1import torch
2from safetensors.torch import load_file
3from transformers import AutoModelForSequenceClassification, AutoTokenizer
4from peft import get_peft_model, LoraConfig
5from huggingface_hub import hf_hub_download
6import os
7
8# compare the base model and the adapter
9base_model_name = "distilbert-base-uncased"
10hf_repo_id = "Qndhm/distilled-bert-imdb-lora-adapter"
11
12# --- load base model and adapter ---
13print(f"loading base model: {base_model_name}")
14model = AutoModelForSequenceClassification.from_pretrained(
15 base_model_name,
16 num_labels=2
17)
18tokenizer = AutoTokenizer.from_pretrained(hf_repo_id)
19
20# --- create the config file
21peft_config = LoraConfig(
22 task_type="SEQ_CLS",
23 r=8,
24 lora_alpha=16,
25 lora_dropout=0.1,
26 target_modules=["q_lin", "v_lin"],
27 modules_to_save=["pre_classifier", "classifier"]#to be used later
28)
29
30# add a null LoRA adapter
31model = get_peft_model(model, peft_config)
32model.print_trainable_parameters()
33
34# load the adapter weights form hub
35print(f"\n downloading weights from hub: {hf_repo_id}")
36weights_path = hf_hub_download(repo_id=hf_repo_id, filename="adapter_model.safetensors")
37adapter_weights = load_file(weights_path)
38
39#compare the keys of adapter and base model
40print("Hub keys of the adapter:", list(adapter_weights.keys()))
41
42# print base model keys
43model_trainable_keys = [k for k, v in model.named_parameters() if v.requires_grad]
44print("base model keys:", model_trainable_keys)
45new_state_dict = {}
46for k, v in adapter_weights.items():
47 #adjust the keys to be consistent
48 new_key = k.replace(".weight", ".default.weight")
49 if "classifier" in new_key:
50 # ...classifier.bias -> ...classifier.modules_to_save.default.bias)
51 if new_key.endswith(".bias"):
52 new_key = new_key.replace(".bias", ".modules_to_save.default.bias")
53 # ...classifier.default.weight -> ...classifier.modules_to_save.default.weight)
54 elif new_key.endswith(".weight"):
55 new_key = new_key.replace(".default.weight", ".modules_to_save.default.weight")
56 new_state_dict[new_key] = v
57
58print("New keys:", list(new_state_dict.keys()))
59print("\n Load weights with new keys")
60model.load_state_dict(new_state_dict, strict=False)
61
62#Test the model from here
63text_pos = "I do not like this movie, it was bad!"
64inputs_pos = tokenizer(text_pos, return_tensors="pt")
65with torch.no_grad():
66 outputs_pos = model(**inputs_pos)
67predicted_class_id_pos = outputs_pos.logits.argmax().item()
68print(f"positive: '{text_pos}' --> prediction: {predicted_class_id_pos}")