When Not to Fine-Tune
Try these first.
Fine-tuning is powerful, but it's not always the right tool. Often, a better prompt, or a bigger model, is enough. Let's test that.
- Powerful, but not always right
- A better prompt?
- A bigger model?
Few-shot prompting
Here, we don't train anything. Instead, we add five examples to the system message. This is called few-shot prompting. Then we score two models, with no fine-tuning. Our tiny model, and Qwen, which is almost four times bigger. Run it. The tiny model still fails. But Qwen gets valid JSON every time, and forty four percent correct. With no training at all.
from transformers import AutoTokenizer, AutoModelForCausalLM
from datasets import load_dataset
from score import score
import ask
EXAMPLES = """Examples:
"Where is my Dune order?" -> {"intent": "order_status", "book": "Dune"}
"How much is Circe?" -> {"intent": "price", "book": "Circe"}
"I want to return Rebecca." -> {"intent": "return", "book": "Rebecca"}
"Is Beloved in stock?" -> {"intent": "stock", "book": "Beloved"}
"My Persuasion arrived torn!" -> {"intent": "complaint", "book": "Persuasion"}"""
ask.SYSTEM = ask.SYSTEM + "\n" + EXAMPLES # a few-shot system message
test = load_dataset("json", data_files="tickets_test.jsonl")["train"]
for name in ["HuggingFaceTB/SmolLM2-135M-Instruct", "Qwen/Qwen2.5-0.5B-Instruct"]:
tok = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(name)
print(f"{name.split('/')[1]:22} {score(model, tok, test)}")SmolLM2-135M-Instruct {'valid_json': '0%', 'correct': '0%'}
Qwen2.5-0.5B-Instruct {'valid_json': '100%', 'correct': '44%'}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)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%}"}Try these first
So try things in this order. First, a clear prompt, with examples. Second, retrieval, where you add facts to the prompt, from your own documents. Third, a bigger model. And only then, fine-tuning. Fine-tune when you need a fixed format, a special style, or a small, fast, cheap model.
| Step | Solves |
|---|---|
| 1. prompt + examples | many tasks, instantly |
| 2. retrieval (RAG) | facts that change |
| 3. a bigger model | harder reasoning |
| 4. fine-tuning | format, style, small and fast |
Our project
For our ticket task, fine-tuning wins. Qwen with a prompt got forty four percent. Our tiny fine-tuned model got eighty six, and it's much faster. But always measure the simple options first. Sometimes they're good enough.
| key | value |
|---|---|
| Few-shot Qwen | 44% correct |
| Fine-tuned tiny | 86% correct |
| Also | faster and cheaper |
| Rule | measure simple options first |
Summary
Let's recap. Try prompts, retrieval, and bigger models first. Fine-tune for format, style, and small fast models. And always measure. Next, sharing our model on the Hub.
Key takeaways- Prompt first
- RAG for facts
- Fine-tune for format and speed