AI Hints
Home›Fine-Tuning LLMs Tutorial›Save, Load and Merge Adapters
Fine-Tuning LLMs · Lesson 56 of 120

Loading Adapters

Base model + adapter.

⏱ 2 min read▶ Video at 1:27:40🎓 Free
Watch this lesson in the Fine-Tuning LLMs courseWatch on YouTube ↗Full Fine-Tuning LLMs course

An adapter on its own does nothing. It needs the base model it was trained on. Luckily, the adapter remembers exactly which base model that was.

  • An adapter alone does nothing
  • It needs its base model
  • It remembers which one

Load from the adapter config

We read adapter config dot json, and print its key settings. Then we load the tokenizer and the base model, using the name stored in the config. Peft model from pretrained puts the adapter on top. Run it. The config remembers the base model's name, the method, LoRA, the rank, alpha, and all seven target layers. And the loaded model answers correctly. Price, for Matilda.

app.pypython
import json
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import PeftModel
from ask import ask

cfg = json.load(open("ticket-lora/adapter_config.json"))
for key in ["base_model_name_or_path", "peft_type", "r", "lora_alpha"]:
    print(f"{key:24} {cfg[key]}")
print(f"{'target_modules':24} {sorted(cfg['target_modules'])}")
tok = AutoTokenizer.from_pretrained(cfg["base_model_name_or_path"])
base = AutoModelForCausalLM.from_pretrained(cfg["base_model_name_or_path"])
model = PeftModel.from_pretrained(base, "ticket-lora")
print(ask(model, tok, "how much is matilda in hardback?"))
Output
base_model_name_or_path  HuggingFaceTB/SmolLM2-135M-Instruct
peft_type                LORA
r                        16
lora_alpha               32
target_modules           ['down_proj', 'gate_proj', 'k_proj', 'o_proj', 'q_proj',
'up_proj', 'v_proj']
{"intent": "price", "book": "Matilda"}
Also uses _setup.py
import shutil
shutil.copytree('/Users/hussain/Docker Complete Course/shared-data/ft_cache/ticket-lora', 'ticket-lora')
Also uses chat.py
import json
from datasets import load_dataset

SYSTEM = "Read the customer's message. Reply with JSON: the intent and the book."

def to_example(row):
    answer = json.dumps({"intent": row["intent"], "book": row["book"]})
    return {"prompt": [{"role": "system", "content": SYSTEM},
                       {"role": "user", "content": row["message"]}],
            "completion": [{"role": "assistant", "content": answer}]}

data = load_dataset("json", data_files={"train": "tickets_train.jsonl",
                                        "test": "tickets_test.jsonl"})
data = data.map(to_example, remove_columns=["message", "intent", "book"])
Also uses ask.py
from chat import SYSTEM

def ask(model, tok, message):
    model.eval()                       # switch off training-only behaviour
    messages = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": message}]
    ids = tok.apply_chat_template(messages, add_generation_prompt=True,
                                  return_dict=True, return_tensors="pt")
    out = model.generate(**ids, max_new_tokens=30, do_sample=False)
    return tok.decode(out[0][ids["input_ids"].shape[1]:], skip_special_tokens=True)
Also uses sft.py
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import LoraConfig
from trl import SFTTrainer, SFTConfig
from chat import data

NAME = "HuggingFaceTB/SmolLM2-135M-Instruct"
tok = AutoTokenizer.from_pretrained(NAME)
model = AutoModelForCausalLM.from_pretrained(NAME)
lora = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05,
                  target_modules="all-linear", task_type="CAUSAL_LM")
args = SFTConfig(output_dir="ticket-lora", num_train_epochs=1, learning_rate=2e-4,
                 per_device_train_batch_size=8, logging_steps=11,
                 eval_strategy="steps", eval_steps=22,
                 save_strategy="no", report_to="none")
trainer = SFTTrainer(model=model, args=args, train_dataset=data["train"],
                     eval_dataset=data["test"], processing_class=tok, peft_config=lora)

Always match the base model

One important rule. Always load an adapter onto the exact base model it was trained on. An adapter trained on SmolL M two won't work on Qwen. Even a different version of the same model can give bad results. The adapter config tells you which one to use.

keyvalue
Rulesame base model, always
Different modelwon't work
Different versioncan give bad results
Checkadapter_config.json

Summary

Let's recap. An adapter needs its base model. The adapter config stores the base model's name. And peft model from pretrained puts the adapter on top. Next, merging an adapter into the model.

Key takeaways
  • Adapter + base model
  • adapter_config.json
  • PeftModel.from_pretrained()
Next up: Merging Adapters — one simple model