Papa Programmer
Lesson 33 of 36

Distillation

9 min read

Optional

Teacher and student

The teacher is a strong, expensive model. The student is smaller. The teacher supplies the training signal, and the student learns to match it on your task. A distilled student often cannot match the teacher everywhere, but it can come close on a narrow job, such as sorting support tickets, at a fraction of the serving cost.

The signal comes in two forms.

  • Generated answers. The teacher writes outputs for your prompts, and you fine-tune the student on them like any dataset. This works through any hosted API, because you need only the text.
  • Soft targets. The teacher's full set of probabilities for each possible output. These carry more information per example, but hosted APIs do not always expose them.

Why soft targets help

A hard label says only "refund". A teacher's probabilities say "refund 90%, billing question 8%, complaint 2%", which tells the student that refund and billing question are close. A temperature setting flattens the probabilities so that the small differences become visible. The program below turns three teacher scores into probabilities at two temperatures, then shows what a hard label and the teacher's soft targets each ask of the student.

python
import math

def softmax(scores, temperature=1.0):
	exps = [math.exp(s / temperature) for s in scores]
	total = sum(exps)
	return [e / total for e in exps]

teacher_scores = [4.0, 2.0, 0.5]
labels = ["refund", "billing question", "complaint"]

for t in (1.0, 3.0):
	probs = softmax(teacher_scores, t)
	print(f"temperature {t}: " + ", ".join(f"{l} {p:.2f}" for l, p in zip(labels, probs)))

student = softmax([2.5, 1.0, 1.5])
print("student:", ", ".join(f"{l} {p:.2f}" for l, p in zip(labels, student)))

hard = [1.0, 0.0, 0.0]
soft = softmax(teacher_scores, 3.0)
for name, target in (("hard label", hard), ("soft targets", soft)):
	gaps = ", ".join(f"{l} {t - s:+.2f}" for l, t, s in zip(labels, target, student))
	print(f"{name:13} change wanted: {gaps}")

It prints:

text
temperature 1.0: refund 0.86, billing question 0.12, complaint 0.03
temperature 3.0: refund 0.55, billing question 0.28, complaint 0.17
student: refund 0.63, billing question 0.14, complaint 0.23
hard label    change wanted: refund +0.37, billing question -0.14, complaint -0.23
soft targets  change wanted: refund -0.08, billing question +0.14, complaint -0.06

At temperature 1 the teacher is almost certain of "refund". At temperature 3 the teacher still prefers "refund", but it shows that "billing question" is a much closer second than "complaint". A student trained on the soft targets learns that ordering. A student trained on the hard label sees only the winner. The student here ranks "complaint" above "billing question", which the teacher does not. The hard label asks it to lower both wrong answers by different amounts and nothing more, while the soft targets ask it to raise "billing question" from 0.14 to 0.28 and to lower "complaint" a little.

Build the dataset carefully

  1. Cover the real task. Choose prompts from real use, including rare and difficult cases, with permission to use them.
  2. Check the licence. Some providers limit using their model's outputs to train another model. Read the terms before you start, as Safety, licences and upkeep explains.
  3. Review the teacher. Sample outputs and filter errors and unsafe text. A student copies mistakes with the same confidence.
  4. Keep the test set clean. Split by prompt before generating, and never include test prompts in the training data, as Training, validation and test sets advises.

Does it pay off?

Distillation adds a one-off cost, which is teacher calls, training and evaluation. It saves money on every request afterwards. The program below finds the number of requests at which the saving covers the cost. The prices are invented to show the calculation, so replace them with yours.

python
teacher_per_request = 0.0120
student_per_request = 0.0008
generate_and_label = 600.0
training_and_evaluation = 250.0

one_off = generate_and_label + training_and_evaluation
saving = teacher_per_request - student_per_request
break_even = one_off / saving
print(f"saving per request: ${saving:.4f}")
print(f"break-even: {break_even:,.0f} requests")
for monthly in (20_000, 200_000):
	print(f"{monthly:>7,} requests a month repay it in {break_even / monthly:.1f} months")

It prints:

text
saving per request: $0.0112
break-even: 75,893 requests
 20,000 requests a month repay it in 3.8 months
200,000 requests a month repay it in 0.4 months

The one-off cost is repaid after about 76 thousand requests. At 20,000 requests a month that takes nearly four months, and at 200,000 a month it takes less than half a month. At very low volume the project may never pay for itself. The sum leaves out evaluation upkeep, so treat it as a first estimate.

What the student loses

A student inherits the teacher's mistakes and often does worse on rare or hard cases, because it saw fewer of them. Compare the student, the teacher and a small untuned baseline on the same held-out set, and read the slices as Evaluating a fine-tuned model shows. Then check the failures with Error analysis and the next round before deciding. The original distillation paper introduced soft targets, and DistilBERT is a well-known worked example.

TeacherStudent
Size and costLarge, expensive to runSmall, cheap to run
RangeBroadNarrow, tuned to one task
Training signalOwn data and trainingTeacher outputs or probabilities
Typical weak spotCost and latencyRare and hard cases
Teacher and student
Smaller, narrowerA student is cheap because it covers less ground.
Soft targets teach moreProbabilities show which wrong answers are near misses.
Copies the faultsA student repeats the teacher's mistakes, so review the outputs.

Your reading position is saved

0%

0 of 36 complete

Contents

Learning tools