AI Hints
Home›Fine-Tuning LLMs Tutorial›Comparing Runs and Error Analysis
Fine-Tuning LLMs · Lesson 88 of 120

Comparing Runs

Which settings won?.

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

Should we use a LoRA rank of two, or sixteen? Guessing is easy. Measuring is better. Let's train two models, and compare them fairly.

  • Rank two, or sixteen?
  • Don't guess
  • Measure and compare

A fair comparison

To compare fairly, change only one setting at a time. Start each run from a fresh model. Use the same data, the same seed, and the same test set. Then any difference comes from the setting you changed.

keyvalue
Changeone setting at a time
Startfrom a fresh model
Keepsame data, seed, test set
Thenthe difference is real

Rank 2 vs rank 16

Here's our experiment. We loop over two ranks. Each run loads a fresh model, so they don't share any learning. Alpha is twice the rank, in both runs. We train for one epoch, then print the trainable parameters, the loss, and the score. Run it. Rank two trains six hundred thousand parameters, and gets only thirteen percent right. Rank sixteen trains almost five million, and gets eighty four percent.

app.pypython
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import LoraConfig
from trl import SFTTrainer, SFTConfig
from datasets import load_dataset
from chat import data
from score import score
NAME = "HuggingFaceTB/SmolLM2-135M-Instruct"
tok = AutoTokenizer.from_pretrained(NAME)
test = load_dataset("json", data_files="tickets_test.jsonl")["train"]   # raw rows for score()
for rank in [2, 16]:
    model = AutoModelForCausalLM.from_pretrained(NAME)          # a fresh model each run
    lora = LoraConfig(r=rank, lora_alpha=2*rank, target_modules="all-linear", task_type="CAUSAL_LM")
    args = SFTConfig(output_dir=f"run-r{rank}", num_train_epochs=1, learning_rate=2e-4,
                     per_device_train_batch_size=8, save_strategy="no", report_to="none")
    trainer = SFTTrainer(model=model, args=args, train_dataset=data["train"],
                         processing_class=tok, peft_config=lora)
    loss = trainer.train().training_loss
    print(f"r={rank:2}  params {trainer.model.get_nb_trainable_parameters()[0]:>9,}  "
          f"train loss {loss:.3f}  {score(trainer.model, tok, test)}")
Output
r= 2  params   610,560  train loss 0.805  {'valid_json': '100%', 'correct': '13%'}
r=16  params 4,884,480  train loss 0.221  {'valid_json': '100%', 'correct': '84%'}
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%}"}

Reading the result

For this task, and one epoch, rank two was too small. Both runs produce valid JSON. But only the bigger rank learned the intents well. With more epochs, rank two might catch up. That would be the next experiment.

keyvalue
Rank 213% correct
Rank 1684% correct
Both100% valid JSON
Next experimentmore epochs for rank 2

Summary

Let's recap. Change one setting at a time. Start every run from a fresh model, with the same data and test set. And compare real scores, not just losses. Next, looking closely at mistakes.

Key takeaways
  • One change at a time
  • Fresh model each run
  • Compare real scores
Next up: Error Analysis — learn from the mistakes