AI Hints
Home›Fine-Tuning LLMs Tutorial›Project: Save, Use and Wrap-up
Fine-Tuning LLMs · Lesson 109 of 120

Project: Merge and Save

The final model.

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

Version three is our winner. Now we turn it into one clean model folder, that any app can load, with no PEFT, and no adapter.

  • Version three wins
  • One clean folder
  • No PEFT needed

Merge, save and reload

First, we load the base model with our adapter. Merge and unload folds the LoRA weights into the base weights. We save the merged model, and the tokenizer, to one folder, and list its files. Then we load that folder, as a normal model, and ask a question. Run it. One folder, with the weights, the tokenizer, and the chat template. And the reloaded model answers correctly.

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), "tickets-v3")
model.merge_and_unload().save_pretrained("riverside-tickets")
tok.save_pretrained("riverside-tickets")
print("saved:", sorted(os.listdir("riverside-tickets")))

final = AutoModelForCausalLM.from_pretrained("riverside-tickets")     # no PEFT needed
tok = AutoTokenizer.from_pretrained("riverside-tickets")
print(ask(final, tok, "Hi, how much is The Hobbit?"))
Output
saved: ['chat_template.jinja', 'config.json', 'generation_config.json',
'model.safetensors', 'tokenizer.json', 'tokenizer_config.json']
{"intent": "price", "book": "The Hobbit"}
Also uses _setup.py
import shutil
shutil.copytree('/Users/hussain/Docker Complete Course/shared-data/ft_cache/tickets-v3', 'tickets-v3')
Also uses chat.py
import json
from datasets import load_dataset

INTENTS = ["order_status", "return", "price", "stock", "complaint"]
SYSTEM = ("Read the customer's message. Reply with JSON: the intent and the book. "
          "The intent must be one of: " + ", ".join(INTENTS) + ".")

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 score.py
import json
from ask import ask

def score(model, tok, rows):
    valid = correct = 0
    for row in rows:
        reply = ask(model, tok, row["message"])
        try:
            answer = json.loads(reply)
        except json.JSONDecodeError:
            continue                       # not JSON: neither valid nor correct
        if not isinstance(answer, dict):
            continue                       # JSON, but not an object
        valid += 1
        if answer.get("intent") == row["intent"] and answer.get("book") == row["book"]:
            correct += 1
    n = len(rows)
    return {"valid_json": f"{valid / n:.0%}", "correct": f"{correct / n:.0%}"}

Adapter or merged?

Should you keep the adapter, or the merged model? Keep both. The adapter is small, and easy to share. The merged model is simpler to deploy, and slightly faster. And it's what you'd convert to GGUF, for Ollama.

keyvalue
Adaptersmall, easy to share
Mergedsimple to deploy, faster
GGUFneeds the merged model
Keepboth

Summary

Let's recap. Merge and unload folds LoRA into the base model. Save the model, and the tokenizer, together. And the merged folder loads with no PEFT at all. Next, we build a small app.

Key takeaways
  • merge_and_unload()
  • Save model + tokenizer
  • Loads without PEFT
Next up: Project: Chat With It — a small support app