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

Merging Adapters

One simple model.

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

Sometimes you want one simple model file, with no PEFT needed to run it. For example, to deploy it with tools that don't know about adapters. For that, we merge the adapter into the base model.

  • One simple model file
  • No PEFT needed
  • Merge the adapter in

What merging does

Remember the LoRA picture. The output was W times x, plus B times A times x. Merging simply adds B times A into W, once, for every layer. Then the adapter can be removed. The model has exactly its original shape, but with the new behaviour built in. And it runs a little faster, with no extra step.

keyvalue
BeforeW·x + B·A·x
MergeW ← W + B·A
Aftera normal model
Bonusslightly faster

Merge and save

We load the base model with the adapter, and ask a question. Merge and unload adds the adapter into the weights, and returns a normal model. We ask the same question again. Then we save the merged model, and its tokenizer, and check the file size. Run it. Both give the same answer. The merged model is a normal llama model. And the file is full size again, five hundred and thirty eight megabytes.

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

NAME = "HuggingFaceTB/SmolLM2-135M-Instruct"
tok = AutoTokenizer.from_pretrained(NAME)
model = PeftModel.from_pretrained(AutoModelForCausalLM.from_pretrained(NAME), "ticket-lora")
print("Adapter:", ask(model, tok, "How much is Emma?"))
merged = model.merge_and_unload()
print("Merged: ", ask(merged, tok, "How much is Emma?"))
print("Type:   ", type(merged).__name__)
merged.save_pretrained("ticket-merged")
tok.save_pretrained("ticket-merged")
size = os.path.getsize("ticket-merged/model.safetensors") / 1e6
print(f"Merged model file: {size:.0f} MB")
Output
Adapter: {"intent": "price", "book": "Emma"}
Merged:  {"intent": "price", "book": "Emma"}
Type:    LlamaForCausalLM
Merged model file: 538 MB
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)

Adapter or merged?

So which should you keep? Keep the adapter when you have many tasks, or want small files. Merge when you deploy one task, and want the simplest, fastest model. You can always keep both. The adapter is the small recipe. The merged model is the finished dish.

Keep the adapter

  • Many tasks, one base
  • Small files
  • Needs PEFT to run

Merge it

  • One task to deploy
  • Full-size file
  • Runs anywhere, a bit faster

Summary

Let's recap. Merge and unload adds the adapter into the weights. The result is a normal model, with the same answers. And it runs without PEFT. Next, a technique that shrinks models even further. Quantization.

Key takeaways
  • merge_and_unload()
  • Same answers
  • A normal, full-size model
Next up: Quantization — fewer bits per number