AI Hints
Home›Fine-Tuning LLMs Tutorial›Beyond LoRA: PEFT, Distillation and Prompting
Fine-Tuning LLMs · Lesson 95 of 120

Distillation

A big model teaches a small one.

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

Big models are smart, but slow, and expensive to run. Small models are fast, and cheap. What if a big model could teach a small one? That's called distillation.

  • Big: smart, but slow
  • Small: fast, cheap
  • A big model teaches a small one

How distillation works

The big model is called the teacher. The small one is the student. First, the teacher answers many real inputs. Then we fine-tune the student on those answers. The student learns to copy the teacher, on just our task.

keyvalue
Teachera big, strong model
Studenta small, fast model
Step 1teacher labels inputs
Step 2fine-tune the student

Labelling with a teacher

Here's the idea in code. A pipeline loads a large teacher model. On a laptop, this would be far too slow, so it's shown, not run. We read a file of unlabelled customer messages. For each one, the teacher writes an answer. And we save the pairs, ready to train our small student.

distil.pypython
import json
from transformers import pipeline
from chat import SYSTEM

teacher = pipeline("text-generation", model="Qwen/Qwen2.5-72B-Instruct")   # big, slow
unlabelled = open("new_messages.txt").read().splitlines()

with open("distilled.jsonl", "w") as f:
    for message in unlabelled:
        messages = [{"role": "system", "content": SYSTEM},
                    {"role": "user", "content": message}]
        answer = teacher(messages, max_new_tokens=40)[0]["generated_text"][-1]["content"]
        f.write(json.dumps({"message": message, "answer": answer}) + "\n")
# then: check the answers, and fine-tune a small student on distilled.jsonl

Things to check

Always check the teacher's answers, because it makes mistakes too. Read the licence of the teacher model, because some forbid training other models on their outputs. And remember, the student usually can't beat its teacher.

keyvalue
Checkthe teacher makes mistakes
Licencesome forbid it
Limitstudent ≤ teacher
Benefitsmall, fast, cheap

Summary

Let's recap. A teacher model labels inputs. A small student learns from those labels. Check the answers, and the licence. Next, when you shouldn't fine-tune at all.

Key takeaways
  • Teacher labels
  • Student learns
  • Check licence
Next up: When Not to Fine-Tune — try these first