AI Hints
Home›Fine-Tuning LLMs Tutorial›Evaluating a Fine-Tuned Model
Fine-Tuning LLMs · Lesson 84 of 120

Perplexity

How surprised is the model?.

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

Perplexity is a number you'll see in many papers, and model cards. It sounds complicated. But the idea is simple. How surprised is the model by the right answer?

  • Seen in papers and model cards
  • Sounds complicated
  • How surprised is the model?

From loss to perplexity

Remember, the loss is the average of minus log probability, for each correct token. Perplexity is just e to the power of the loss. A perplexity of one means the model was certain, and right. A perplexity of ten means it was as unsure as choosing among ten tokens.

keyvalue
Lossaverage −log p per token
Perplexitye ^ loss
1certain, and right
10like picking from 10 tokens

Measuring perplexity

Here's how we measure it. We turn off gradients, because we're only measuring. For each test row, we build the prompt tokens, and the answer tokens. Minus one hundred labels mean only the answer is scored. Then we average the losses, and take e to the power. Run it. The base model scores about eight and a half. Our fine-tuned model scores one point zero three. It's almost never surprised by the right answer.

app.pypython
import math, torch
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import PeftModel
from chat import data
NAME = "HuggingFaceTB/SmolLM2-135M-Instruct"
tok = AutoTokenizer.from_pretrained(NAME)
torch.set_grad_enabled(False)                # we only measure, no training
def perplexity(model, rows):
    losses = []
    for row in rows:
        prompt = tok.apply_chat_template(row["prompt"], add_generation_prompt=True)["input_ids"]
        answer = tok(row["completion"][0]["content"])["input_ids"]
        labels = torch.tensor([[-100] * len(prompt) + answer])   # score the answer only
        losses.append(model(input_ids=torch.tensor([prompt + answer]), labels=labels).loss.item())
    return math.exp(sum(losses) / len(losses))
base = AutoModelForCausalLM.from_pretrained(NAME).eval()
print(f"base perplexity:       {perplexity(base, data['test']):6.2f}")
tuned = PeftModel.from_pretrained(base, "ticket-lora").eval()
print(f"fine-tuned perplexity: {perplexity(tuned, data['test']):6.2f}")
Output
base perplexity:         8.45
fine-tuned perplexity:   1.03
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)
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%}"}

When to use it

Perplexity is quick, and needs no generation. It's great for comparing models on the same data. But low perplexity doesn't guarantee good answers. And you can only compare perplexity between models that share the same tokenizer.

keyvalue
Goodfast, no generation
Usecompare models, same data
Limitnot a quality guarantee
Rulesame tokenizer only

Summary

Let's recap. Perplexity is e to the power of the loss. Lower means less surprised. It's fast, but it doesn't guarantee good answers. Next, we put it together in an evaluation loop.

Key takeaways
  • e ^ loss
  • Lower is better
  • Same tokenizer only
Next up: An Evaluation Loop — score every checkpoint