Before and After
See the difference.
Numbers are good, but seeing is believing. Let's put the original model, and our fine-tuned model, side by side, on the same customer messages.
- Seeing is believing
- Original vs fine-tuned
- Same messages
Side by side
Our trained adapter was saved in a folder called ticket LoRA. We load the original model, and a second copy with the adapter on top, using peft model from pretrained. Then we ask both about two messages. Run it. Before fine-tuning, the model says sorry, or describes the message, in long sentences. After, it gives exactly the JSON our app needs. The right intent, and the right book.
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import PeftModel
from ask import ask
NAME = "HuggingFaceTB/SmolLM2-135M-Instruct"
tok = AutoTokenizer.from_pretrained(NAME)
base = AutoModelForCausalLM.from_pretrained(NAME)
tuned = PeftModel.from_pretrained(AutoModelForCausalLM.from_pretrained(NAME), "ticket-lora")
for msg in ["Do you have Rebecca in stock?", "my copy of Emma arrived with torn pages"]:
print("MESSAGE:", msg)
print(" before:", ask(base, tok, msg)[:70])
print(" after: ", ask(tuned, tok, msg))MESSAGE: Do you have Rebecca in stock?
before: I'm sorry for the inconvenience, but as an AI, I don't have the abilit
after: {"intent": "stock", "book": "Rebecca"}
MESSAGE: my copy of Emma arrived with torn pages
before: The customer's message indicates that the book arrived with torn pages
after: {"intent": "complaint", "book": "Emma"}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)Why the prompt alone failed
Notice that the original model got the same system message, asking for JSON. It still didn't follow it. A small model struggles with instructions like this. But a few hundred examples taught it the exact behaviour. This is where fine-tuning shines, especially for small, cheap models.
| key | value |
|---|---|
| Same system message | both models got it |
| Original | ignored the format |
| Fine-tuned | follows it every time |
| Lesson | examples beat instructions |
Summary
Let's recap. Peft model from pretrained puts a saved adapter on a model. The original model ignored our format. The fine-tuned one follows it exactly. Next, how to read the loss, and spot problems.
Key takeaways- PeftModel.from_pretrained()
- Before: chatty
- After: clean JSON