Build Your Own LLM, Lesson 11: Instruction Tuning and Chat Templates

Build Your Own LLM, Lesson 11: Instruction Tuning and Chat Templates 1

📎 This article includes 4 downloadable practice files ↓

⏱ 2 min read

A model trained only on books continues text; it doesn’t answer questions. Instruction tuning trains it on many examples of “user asks, assistant answers”, formatted with special markers so it learns the turn-taking.

Advertisement
In this article
  1. Chat templates
  2. Learn only from the answers
  3. Where the data comes from
  4. Practice

Chat templates

<|user|>
What does VLOOKUP do?
<|assistant|>
It finds a value in the first column of a table and returns a value from another column.<|end|>

The markers are special tokens the model learns to recognise. Every model family uses its own format, so always apply the template from the model card (Hugging Face tokenizers have apply_chat_template()).

Learn only from the answers

You don’t want the model to learn to write questions; you want answers. Set the labels for prompt positions to −100, which PyTorch’s cross-entropy ignores:

mask = [0] * len(prompt) + [1] * len(answer)
labels = torch.where(mask == 1, ids, torch.tensor(-100))

Where the data comes from

  • Curated question-answer sets written by people.
  • Your own domain: past support tickets and their resolutions (anonymised).
  • Synthetic data generated by a larger model, then reviewed.
⚠️ Never put customer names, PAN, Aadhaar, salaries or other personal data into fine-tuning sets. Models can repeat training data word for word.

After instruction tuning, models are often further aligned with human preference data (RLHF, DPO) to be more helpful and safe.

Practice

Run the script and add two of your own question-answer pairs.

📎 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 11 scriptTested script for this lesson.
    ⬇ PY · 911 B
  • 📄
    Expected outputWhat the script printed in our test run (your numbers will be close).
    ⬇ TXT · 371 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 *