Build Your Own LLM, Lesson 9: Evaluating a Model β€” Loss, Perplexity and Test Prompts

Build Your Own LLM, Lesson 9: Evaluating a Model β€” Loss, Perplexity and Test Prompts 1

πŸ“Ž This article includes 4 downloadable practice files ↓

⏱ 2 min read

“It looks good” isn’t a measurement. Language models are compared with a few standard numbers, plus a set of prompts you check by eye every time you change something.

Advertisement
In this article
  1. Loss and perplexity
  2. Fixed test prompts
  3. Beyond loss
  4. Practice

Loss and perplexity

Training minimises cross-entropy loss: how surprised the model is by the real next token. Perplexity = eloss, roughly “how many tokens it is choosing between”. A model guessing randomly among 40 characters has perplexity 40; ours scored about 1.1 on held-out text because the sample is so repetitive.

losses = [model(*get_batch(val, 64, 32))[1].item() for _ in range(20)]
avg = sum(losses) / len(losses)
print(avg, math.exp(avg))
⚠️ Perplexity is only comparable between models with the same tokenizer on the same text. A character model and a word model can’t be compared this way.

Fixed test prompts

Keep 10-20 prompts that matter for your use, generate with a fixed seed and low temperature after each training run, and compare. Regressions (it used to answer, now it rambles) show up immediately.

Beyond loss

  • Benchmarks (multiple-choice tests of knowledge and reasoning) for general models.
  • Task metrics: accuracy for classification, exact match for extraction.
  • Human review for tone, helpfulness and safety, which no number captures well.
πŸ’‘ Hold out data the model never saw, including at the document level. If the same sentence appears in train and validation, scores look better than reality.

Practice

Run after lesson 7. Then retrain for fewer steps and compare the perplexity.

πŸ“Ž Practice files for this article

⬇ Download all 4 files (ZIP Β· 5 KB)

  • 🐍
    tinygpt.py (shared model code)The GPT model, tokenizer, batching and generation used in lessons 6-12.
    ⬇ PY Β· 4 KB
  • 🐍
    Lesson 9 scriptTested script for this lesson.
    ⬇ PY Β· 917 B
  • πŸ“„
    Expected outputWhat the script printed in our test run (your numbers will be close).
    ⬇ TXT Β· 243 B
  • πŸ“„
    sample.txtSmall training text; swap in any public-domain book for better results.
    ⬇ TXT Β· 83 KB

Free to use for learning. Files with macros (.bas) are plain text β€” import them with Alt+F11 β†’ File β†’ Import File, and always test on a copy.

✨ Ask AI about this article

Stuck on a step? Ask a question and the AI answers using this article.

Free Β· AI can be wrong

Leave a Reply

Your email address will not be published. Required fields are marked *