Build Your Own LLM, Lesson 7: Train a Tiny GPT on Your Own Text

Build Your Own LLM, Lesson 7: Train a Tiny GPT on Your Own Text 1

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

⏱ 2 min read

Time to train a real (tiny) GPT. The model in tinygpt.py is the same design as GPT-2, only smaller: token embeddings plus position embeddings, a stack of transformer blocks, a final LayerNorm and a linear layer that predicts the next character.

Advertisement
In this article
  1. The training loop
  2. Train vs validation loss
  3. Scaling up
  4. Practice

The training loop

model = TinyGPT(tok.vocab_size, d_model=96, n_heads=4, n_layers=3, block_size=64)
opt = torch.optim.AdamW(model.parameters(), lr=3e-3)
for step in range(steps + 1):
    xb, yb = get_batch(train, 64, 32)        # 32 random 64-character windows; yb = xb shifted by one
    _, loss = model(xb, yb)
    opt.zero_grad(); loss.backward(); opt.step()

Every window teaches 64 predictions at once: after “E” comes “x”, after “Ex” comes “c”… That’s why language models train efficiently.

Train vs validation loss

Keep the last 10% of the text aside. If training loss keeps falling but validation loss rises, the model is memorising rather than learning patterns (overfitting): use more text, add dropout, or stop earlier.

In our test the small, very repetitive sample file reached a validation loss of about 0.1 in 300 steps (around 40 seconds on a laptop CPU), meaning the model has essentially memorised the sentences.

πŸ’‘ For something more interesting, train on a public-domain book from Project Gutenberg (a few hundred KB) for 2,000-5,000 steps: python lesson-07-train-tiny-gpt.py book.txt 3000. The output will invent new sentences in the book’s style.

Scaling up

Knob Effect
d_model, n_layers Bigger brain; slower; needs more data
block_size Longer memory (context)
Steps, data The biggest lever for quality
GPU (device=”cuda”) 10-50Γ— faster training

Practice

Run the script on sample.txt, then on a book of your choice, and compare the generated text.

πŸ“Ž 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 7 scriptTested script for this lesson.
    ⬇ PY Β· 1 KB
  • πŸ“„
    Expected outputWhat the script printed in our test run (your numbers will be close).
    ⬇ TXT Β· 270 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 *