09 · Distillation
A 0.5B student trained on 2,946 labels written by a 7B teacher rose from 44.0% to 58.6% exact match, closing 69% of the gap to the teacher's 65.2%, at one fifth of the GPU time per answer; it also copied the teacher's exact wrong query on 37.9% of the questions the teacher got wrong.
- Part 3
- Beyond supervised
- Model
Teacher Qwen2.5-7B-Instruct (4-bit), student Qwen2.5-0.5B-Instruct- Data
- Questions from lesson 3, labelled by the teacher
- Hardware
- One T4, in Google Colab
Lessons 4 and 5 trained a model on gold answers: a person or a database had already written the right query for every question. Often there is no such file. A team has the questions, from logs, and a large model that answers them well enough, but the large model is too slow or too dear to serve. Distillation moves the large model's behaviour into a small one: the large model (the teacher) answers the questions, and the small model (the student) is trained on those answers.
Here it worked in part. The Student closed 69% of the 21.2-point gap to the Teacher and then stopped short of it, and it copied some of the Teacher's mistakes along with its answers. The result comes first and the exact setup, time and cost are in How it was built at the end.
Distillation closed 69% of the gap to the teacher; the same student trained on gold answers passed it, by less than the noise
Exact match with the gold query on 500 test questions, with the 95% interval; shaded: the distance from the untrained student to the teacher
1Several teams have published what that bought them. The table gives each claim as the source reports it:
| Source | Teacher and student | What they report |
|---|---|---|
| Method Financial, with OpenPipe (conference talk) | o3-mini outputs on production banking inputs train Llama 3.1 8B | The 8B model did not quite match o3-mini, beat GPT-4o on this workload, met the error threshold set beforehand and cost less than required; no figures for the 8B are given |
| Instacart, query understanding | An offline retrieval pipeline tags head queries; Llama-3-8B with LoRA learns the tags for the long tail | F1 95.7% against 95.8% for the larger model; complaints about poor tail-query results down 50% in an A/B test |
| Booking.com, with Amazon Science | Llama-3.1 70B teacher, TinyLlama 1.1B student, plus Medusa heads | Distillation closed more than 90% of the student's gap to the teacher; the final model matched the teacher's quality at 10 to 20 times the speed |
| Pinterest, search relevance (company paper) | An LLM relevance teacher labels 30M query and Pin pairs for a light student | Five-level accuracy 0.548, against 0.484 for a student trained on 0.3M human labels |
| Intercom, Fin | Production LLM extractions train Qwen3 models | Qwen3 14B reached an answer rate of 63.4% against 63.3% for GPT-4.1; the 8B models reached 51.0% and 55.0% |
| Shopify, Sidekick | Frontier models write corrected trajectories; a smaller model is trained on them | Serving cost estimated at about $1M a year against $27M on a frontier model (the post's estimate) |
All six are the companies' own reports, not independent measurements. They share a shape: a large model that is good but costly, labels written by that model, a smaller model trained on them. This lesson builds that shape on the course task, a question about a table in and one SQLite query out, and measures what it gives and what it costs. The teacher is Qwen2.5-7B-Instruct loaded in 4-bit, as in lesson 5. The student is Qwen2.5-0.5B-Instruct, about 15 times fewer parameters (7.6 billion against 0.49 billion), trained with lesson 4's LoRA recipe. The questions come from the training split. The gold answers exist but are used only to check the teacher's labels and to train one comparison model.
1. Why copy a model
Three things decide whether it is worth doing.
- No gold answers. Logs hold millions of questions and no one has written their answers. A model can.
- A teacher you cannot afford to serve. Method Financial's first month of GPT-4 traffic cost $70,000, according to its talk with OpenPipe, and its stated plan was at least 16 million requests a day within a latency of 200 milliseconds. A reasoning model that takes seconds per answer cannot meet that. Instacart's teacher is an offline pipeline where latency does not matter; its student serves the long tail of rare queries in real time.
- A quality bar you can state. Method Financial measured first what error the downstream checks could tolerate (about 9%) and then asked whether a distilled 8B model stayed under it. The target decides whether a student that sits below the teacher is a success.
Distillation does not make a model better than its teacher by itself. It buys speed and memory, and what it costs in quality is the subject of sections 6 and 9.
2. What gets copied
A student learns from the teacher's examples. It does not inherit the teacher's abilities by name or size. Compare the student's results on new tasks and keep the source of training examples visible.
Hinton, Vinyals and Dean (2015) introduced distillation for classifiers. The student is trained to match the teacher's probabilities for every class, not only its top choice. With teacher logits , student logits and a temperature that flattens the distributions, define
for the teacher's and the student's softened probabilities. The loss mixes the ordinary cross-entropy against the true label with the distance to the teacher:
The gradient of the second term with respect to a student logit is . At a high temperature and with logits centred at zero it approaches for classes, which says that distillation then amounts to matching logits (Hinton's Equations 2 and 4, whose letters are the reverse of the ones used here). Because the gradient shrinks as , the term is multiplied by so that it stays at the scale of the hard-label term. The paper's speech experiment shows the effect: a single distilled model reached 60.8% frame accuracy, against 58.9% for the baseline and 61.1% for the ten-model ensemble it learned from.
A language model produces a sequence, not one class, and the teacher's full distribution over sequences is a sum over exponentially many outputs. Kim and Rush (2016) replaced it with the teacher's single most likely output , found by beam search:
The right-hand side is ordinary supervised fine-tuning on the teacher's text. That is what this lesson does, with greedy decoding as the search. It works when a teacher API returns only text. Partial top-token log probabilities alone cannot recover the full teacher distribution. The cost is that the student sees one answer per question and never the probability the teacher gave to the alternatives. Whether that loses much is a measurement: section 5 makes it for this teacher, and section 8 checks the student's probabilities afterwards.
Hard and soft targets. This is sequence-level hard distillation. The student learns from one chosen SQL sequence per prompt. TRL’s DistillationTrainer matches teacher next-token probabilities on student-generated continuations. NVIDIA ModelOpt’s KDTrainer also supports logit-level distillation. An encoder classifier can learn probabilities over decision classes. The advanced lesson audits teacher accuracy by class, chooses checkpoints using gold validation labels and measures expected calibration error (ECE) before and after temperature scaling. TRL Distillation Trainer · NVIDIA ModelOpt KDTrainer · Distil traces and protect existing skills
Commercial terms. Review the applicable terms for using a frontier model to draft tasks or verifiers and for feeding its recorded answers, tool calls or rollouts directly into another model’s training. These are distinct uses and each needs review. For example, the OpenAI Services Agreement restricts using outputs to develop competing AI models and defines specific exceptions for eligible internal classifiers and for customising models through its services. Check the agreement and any order form for the product and intended distribution. OpenAI Services Agreement, section 3.3 and definitions
3. The gap and the teacher's price
Both models answer the same 500 test questions as lessons 4 and 5, with the zero-shot prompt, greedy decoding and batches of 16. The student loads in fp16; the teacher loads in 4-bit, each decode step rebuilding its weights to fp16, as lesson 5 measured.
bnb_config = BitsAndBytesConfig(
load_in_4bit=True, bnb_4bit_quant_type="nf4",
bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype=torch.float16)
# device_map takes the GPU number (0), not "cuda": accelerate 1.6.0 fails
# on a 4-bit model with "cuda"
teacher = AutoModelForCausalLM.from_pretrained(
TEACHER_ID, quantization_config=bnb_config,
torch_dtype=DTYPE, device_map={"": 0}).eval()
# 500 answers at batch 16, then 12 answers one at a time
evaluate("teacher", teacher, tok, single=True)| System | Runs | Exact (±) | ms per answer, batch 16 | One at a time, ms | Weights | Peak GPU |
|---|---|---|---|---|---|---|
| Student, untrained | 92.8% | 44.0% (±4.4) | 108 | 801 | 0.99 GB | 1.09 GB |
| Teacher | 98.6% | 65.2% (±4.2) | 388 | 1,303 | 5.44 GB | 6.01 GB |
Runs means the query executes in SQLite against the question's schema; the tables are empty, so it says the query is valid, not that it is right. Exact means the query equals the gold text after normalisation. The ± is the 95% interval, , and differences smaller than it are not evidence. The gap to close is 21.2 points of exact match, far outside it.
4. Are the labels usable?
The teacher answers 3,000 questions drawn at random from the training split, with the same prompt. The prompts are sorted by length so that each batch carries little padding, and run in batches of 32.
def label(model, rows_, batch=LABEL_BATCH):
"""Greedy answers from `model`, shortest prompts first."""
prompts = [zero_shot(r) for r in rows_]
lengths = [len(tok.apply_chat_template(p, tokenize=True,
add_generation_prompt=True)) for p in prompts]
order = np.argsort(lengths, kind="stable")
answers_sorted, ms = generate(model, tok, [prompts[i] for i in order],
batch=batch)
answers = [None] * len(rows_)
for position, i in enumerate(order):
answers[i] = answers_sorted[position] # back to the original order
return answers, msIt took 10.1 minutes, 201 ms per label at batch 32. That is the main cost of the method, and it scales with the number of labels.
A teacher's output is data, and data gets checked. The filter is a program that needs only the schema, which is part of every question: a label is kept if it is not empty, is one statement, starts with SELECT, and runs in SQLite against the question's schema.
def check_label(r, raw):
"""'keep' or the reason a label is dropped. Needs only the schema."""
sql = clean_sql(raw)
if not sql:
return "empty"
if ";" in sql.rstrip().rstrip(";"):
return "more than one statement"
if not sql.lower().startswith("select"):
return "not a SELECT"
if runs(r["context"], sql) is not None: # the strongest check here
return "does not run in SQLite"
return "keep"The filter dropped 54 of 3,000 teacher labels, and about two in three of the labels it kept match the gold query
Teacher labels for 3,000 training questions. Left: the program's verdicts, which need only the schema. Right: exact match with the gold query, which the distilled student never sees
2The filter kept 2,946 of 3,000, a keep rate of 98.2%. It dropped 52 labels that do not run and 2 that hold more than one statement. Panel b is a diagnosis against the gold answers, which the student never sees. The teacher matches the gold text on 66.0% of its labels, close to its 65.2% on the test set. The dropped labels match on 7.4% of 54, so the filter removes labels that are nearly all wrong. Execution cannot tell a right query from a wrong one on an empty table, though, so it removes broken labels, not mistaken ones: 32.9% of the kept labels are not the gold query. Some are right in another form, as these four kept labels show:
gold : ... WHERE tyres = "g" AND chassis = "d3 d4" AND driver = "jan lammers"
teacher: ... WHERE driver = 'jan lammers' AND chassis = 'd3 d4' AND tyres = 'g'
same conditions, in another order
gold : ... WHERE year_built = 1865
teacher: ... WHERE year_built = "1865"
the number written as text
gold : ... WHERE score = 65 - 70 - 72 = 207
teacher: ... WHERE score = '65-70-72=207'
a different query
gold : ... AND country_of_origin = "united states"
teacher: ... AND country_of_origin = 'United States'
capital letters in a literalThe student will be trained on them as written. That is what distillation transfers: the teacher's behaviour, mistakes included.
The practice matches what teams report. BMW's engineers, writing about training a small model on a large model's synthetic examples, put it in one sentence: "data that violates your compliance gates teaches the model to violate them". Their judge model drops candidate pairs that fail checks such as preserved identifiers and valid structure; this lesson's filter is the same idea with a program in place of the judge (the post is AWS's account of a pilot, not an audited result). Instacart relies on the other half of the arrangement: its teacher runs offline, so its cost per label does not matter, and only the student's does.
5. One answer for a distribution
Training on one answer per question is a good approximation only if the teacher puts most of its probability on that answer. The notebook measures it. For 64 test questions it teacher-forces the teacher's own answer and records the probability it gave to the whole answer, the product of its token probabilities.
@torch.inference_mode()
def answer_logprobs(model, p_ids, a_ids):
"""Log-probabilities over the vocabulary at each answer position,
teacher-forced on the given answer."""
ids = torch.tensor([p_ids + a_ids], device=DEVICE)
start = len(p_ids) - 1
logits = model(ids).logits[0, start:start + len(a_ids)].float()
return torch.log_softmax(logits, dim=-1)
# per position, the 50 likeliest tokens are stored for section 8
top_lp, top_i = lp.topk(TOP_K, dim=-1)
# probability of the whole answer = product of its token probabilities
seq_prob = np.array([r_["own_lp"].sum().exp().item() for r_ in ref])This teacher puts a median of 90% of its probability on the one answer it writes, so one answer stands in for its distribution
a: probability the teacher gives to its own whole answer, 64 test questions, by decile. b: the same quantity in the paper that introduced sequence-level distillation (translation, a different task)
3The mean probability of the whole answer is 0.80 and the median 0.90; 83% of the answers sit above 0.5. The teacher's tokens are nearly all confident: the mean token probability is 0.990, and 97% of the 1,598 positions have a written token above 0.9. The 50 stored tokens hold at least 0.992 of the probability at every position. For this task and this teacher, one answer is close to the whole distribution, which is why sequence-level training loses little here. It would not on an open-ended task, where the teacher's probability spreads over many acceptable answers.
Kim and Rush measured the same quantity on translation, where it is far lower: the probability of the greedy output was 1.3% for their teacher and 0.9% for a student trained on gold translations, and 16.9% for a student trained on the teacher's output. Training on one teacher output made the student's probability mass concentrate on it. The figures are theirs, on a different task, and are shown for contrast, not as a comparison with ours.
6. Does the student learn it?
The student is Qwen2.5-0.5B-Instruct with a LoRA adapter, trained with lesson 4's settings: rank 16 on every linear layer, learning rate 2e-4 with cosine decay, an effective batch of 16, one epoch, loss on the answer only. The trainable part is 8,798,208 parameters, 1.75% of the model. Two things differ from lesson 4, both because the model is smaller: no gradient checkpointing and no validation passes. The adapter is merged into the fp16 weights before scoring, which is how it would be served.
# (question, teacher's answer) for the 2,946 labels that passed the filter
distilled = examples_for(N_LABEL, filtered=True)
train_stats["distilled"] = train_student("distilled", distilled)
serve("student distilled (filtered)", "distilled") # merge adapter, score
# the upper bound for the same questions: identical recipe, gold answers
train_student("gold", [(r, r["answer"]) for r in pool])The distilled run took 1.8 minutes at 3,193 padded tokens per second and a peak of 6.96 GB; the adapter is 35.2 MB.
Figure 1, at the top of the page, gives the three systems against the gap.
The distilled student scored 58.6% (±4.3), 14.6 points above the untrained student, which is 69% of the 21.2-point gap and far outside the noise. It still sits 6.6 points below the teacher's 65.2%, more than the ±4.2 on either, so the distilled student is below its teacher on these questions. It also runs more often than before, 97.4% against 92.8%, though less often than the teacher's 98.6%.
The gold-trained student, the same questions with human answers, scored 68.2%. That is 3.0 points above the teacher, and each is ±4.1 to ±4.2, so the test cannot say the gold-trained student beats the teacher; it matches it at least. What it does show is the price of having no gold answers: 9.6 points between the distilled student and the gold-trained one, on the same questions. A teacher that reaches 65.2% cannot teach a student much more than its own ceiling, whereas a gold answer is not limited by it.
7. The filter, and how many labels
What did the filter buy? The same pool with the 54 dropped labels left in gives a student at 57.2%, against 58.6% with the filter: 1.4 points, inside the ±4.3 interval of each. The test cannot say the filter helped. Filtering 54 labels out of 3,000 is a small intervention, and these labels are broken queries that are rare. Execution filtering cost a few lines and no time, and it removes the labels that are certainly wrong, so it stays in the recipe; the data cannot show that it was needed.
How many labels are enough? The distilled recipe on the first quarter and half of the pool, after filtering:
More teacher labels kept helping, by amounts the test cannot separate step to step; Pinterest's student rose the same way at 6M to 30M
a: exact match of the distilled student against the number of filtered teacher labels it trained on (±4.3 points each). b: Pinterest's search-relevance student, accuracy against the number of labels (company paper)
4Seven hundred and thirty labels, half a minute of training and about two and a half minutes of teacher time, already lifted the student from 44.0% to 54.2%. Doubling to 1,471 gave 55.4% and doubling again 58.6%. The direction is up at each step, and the top and the bottom of the curve differ by 4.4 points, about one interval. Adjacent points are inside each other's noise, so the curve says that more labels did not hurt and probably helped, not how much each doubling is worth. Nowhere has it reached the teacher.
Pinterest's relevance paper shows the same direction at a much larger scale: a student trained on 0.3 million human labels reached an accuracy of 0.484, and students trained on 6, 12 and 30 million teacher labels reached 0.535, 0.539 and 0.548. It is a company-reported result, on a different task, with a human-label student as the baseline. Its point carries over: a teacher's labels are cheap to produce in bulk, so a student can see far more of them than humans could write, and in their table the accuracy kept rising from 6 to 30 million labels, in smaller steps. A teacher that labels cheaply is a source of data, and the curve is where its price goes.
8. How close are the probabilities?
No student was trained on the teacher's probabilities. They were trained on its text. The notebook still measures how far each student's probabilities are from the teacher's, over the 64 stored answers and the teacher's 50 likeliest tokens at each of the 1,598 positions:
def fidelity(model):
"""KL over the teacher's 50 likeliest tokens, top-1 agreement with its
likeliest token, and mean log-loss on the teacher's tokens."""
kl_sum, agree, nll, count = 0.0, 0, 0.0, 0
for (p_ids, a_ids), r_ in zip(fid_seqs, ref):
lp = answer_logprobs(model, p_ids, a_ids).cpu()
top_p, top_i = r_["top_p"], r_["top_i"]
kl_sum += (top_p * (top_p.log() - lp.gather(1, top_i))).sum().item()
agree += int((lp.argmax(-1) == top_i[:, 0]).sum())
nll -= lp[torch.arange(len(a_ids)), torch.tensor(a_ids)].sum().item()
count += len(a_ids)
return {"KL to teacher": kl_sum / count,
"top-1 agreement": agree / count,
"log-loss on teacher tokens": nll / count}The distilled students ended nearer the teacher's probabilities than before, though no student was trained on them; gold-trained ended farthest
Measured on the teacher's own answers to 64 test questions (1,598 positions), over its 50 likeliest tokens at each position
5The untrained student already agrees with the teacher's likeliest token at 95.5% of positions, because both write mostly the same SQL. Training on the teacher's labels cut its KL from 0.162 to 0.074 and its log-loss from 0.189 to 0.100, and raised top-1 agreement to 97.5%. The KL falls at each step of the curve (0.098, 0.085, 0.074), and the filtered and unfiltered students are the same within the sample (0.074 and 0.076). The gold-trained student sits farthest: KL 0.287 and log-loss 0.319, worse than the untrained student's. It has learned the task from a different source and writes in the gold dataset's style, for example double-quoted lowercase literals where the teacher writes single-quoted ones. That reading follows the kept-label examples in section 4; the notebook does not test it. What the panels do show is that sequence-level training moved the student's probabilities towards the teacher's although they were never an objective. This is a measurement on 64 questions, so the ordering of the first and last rows is clear and the third decimal is not evidence.
9. What does the student inherit?
Distillation transfers behaviour, so it transfers the teacher's mistakes. The test questions give three counts: how the student does where the teacher is right, how it does where the teacher is wrong, and how often in the second case it writes the same wrong query as the teacher.
Where the teacher was wrong, the student wrote the teacher's exact query 37.9% of the time, and was right 22.4%; the gold-trained student was right 39.1%
Exact match on the 500 test questions, split by whether the teacher was right (a); the cause of every miss for the teacher and the two students trained on the full pool (b)
6The teacher is right on 326 of the 500 questions and wrong on 174. On the 326 the distilled student is right on 77.9%, against 83.7% for the gold-trained student. On the 174 the distilled student is right on 22.4% and writes the teacher's exact wrong query on 37.9%, 66 questions. The gold-trained student, never shown those mistakes, is right on 39.1%. Over all 500 questions the distilled student and the teacher write the same query on 64.0%; the gold-trained student and the teacher agree on 61.2%.
Two of the notebook's printed misses, where the teacher's answer and the student's differ from the gold query:
for a Goals Against greater than 42 what is the number of losses?
- Gold
- SELECT AVG(losses) FROM table_name_9 WHERE goals_against > 42
- Teacher
- SELECT losses FROM table_name_9 WHERE goals_against > 42
- Student
- SELECT SUM(losses) FROM table_name_9 WHERE goals_against > 42
Both miss the aggregate, in different ways; the Student did not copy the Teacher here.
What is the lowest Overall for the wide receiver in a round less than 2?
- Gold
- SELECT MIN(overall) FROM table_name_93 WHERE position = "wide receiver" AND round < 2
- Teacher
- SELECT MIN(overall) FROM table_name_93 WHERE position = 'WR' AND round < 2
- Student
- SELECT MIN(overall) FROM table_name_93 WHERE position = 'wide' AND round < 2
The Teacher abbreviates the literal and the Student writes a different wrong one, in the Teacher's single-quoted style.
The distilled student is bounded by its teacher, and a share of its misses are the teacher's own. The cause table adds a second view. The distilled student's misses are mostly the teacher's kind, wrong aggregate, operator or clause (83 against 73), and it also writes queries that do not run more often than the teacher (13 against 7 of 500). The gold-trained student has the fewest wrong aggregates and clauses, 52, and 15 queries that do not run.
Two reports in the cases above show the same pattern at company scale. Intercom trained a separate classifier on a million examples and found that when its output disagreed with the ground truth, it was mostly the teacher's mistakes, not the student's. It also found that size matters: Qwen3 14B reached the answer rate of its GPT-4.1 baseline (63.4% against 63.3%), while the 8B models reached 51.0% and 55.0%, and a student trained only on hard resolutions reached 36.4%. A student trained on a biased slice of the teacher's output inherits the bias. Pinterest's result is the other side of the same coin: with 30 million teacher labels its student beat one trained on 0.3 million human labels, so a teacher's labels add volume that human labels could not, and its mistakes come with it.
10. Cost and payback
The distilled student answers in 79 ms at batch 16 against the teacher's 388, 4.9 times less GPU time, and one request alone takes 646 ms against 1,303, 2.0 times less. Its weights take 0.99 GB against 5.44, 5.5 times less. (The untrained student is slower than the distilled one, 108 ms, with no cause measured here.)
Building the student cost 604 seconds of labelling and 109 seconds of training, 713 GPU-seconds once. Each answer then saves 308 ms of GPU time, so the build pays back when
with and the teacher's and student's GPU-seconds per answer.
The student is 4.9 times cheaper per answer and repays its 713 GPU-seconds of building after 2,311 answers
a: exact match against GPU-seconds per 1,000 answers (batch 16, one T4; bubble area = weights in memory). b: cumulative GPU-seconds to serve N answers, teacher against distilled student
7Read the break-even with its limits. It counts GPU time only: it leaves out the 15 GB teacher download, the evaluation, your time, and the quality given up, 6.6 points of exact match against the teacher. It uses your own GPU for the teacher; if the teacher is a paid API, the same sum holds with the API's price per label in place of the 604 seconds, and the student then runs on hardware you own. And it assumes the traffic is high enough to reach 2,311 answers, which a production workload reaches quickly.
Published results show where the saving goes at scale. Booking.com and Amazon Science report a 1.1B student that matched a 70B teacher's quality at 10 to 20 times the speed, from distillation (about six times) and Medusa heads, which decode several tokens in parallel (a further 2 to 3.6 times). Shopify's team estimates serving one of its agents on a frontier model at about $27M a year and a fine-tuned model at about $1M, an estimate in its post, not a bill. Those are company reports with no audited costs. Their direction agrees with the 4.9 times measured here; their size depends on the models, the hardware and the traffic.
11. What to keep
| System | Exact (±) | Gap closed | ms per answer, batch 16 | Weights |
|---|---|---|---|---|
| Student, untrained | 44.0% (±4.4) | 0% | 108 | 0.99 GB |
| Student, distilled | 58.6% (±4.3) | 69% | 79 | 0.99 GB |
| Student, trained on gold | 68.2% (±4.1) | 114% | 81 | 0.99 GB |
| Teacher | 65.2% (±4.2) | 100% | 388 | 5.44 GB |
If you have a task like this one:
- Measure the thresholds first. The accuracy, the latency and the cost per answer you can accept decide whether a Student 6.6 points below its Teacher is good enough. Method Financial set its error threshold before training.
- Label with the best teacher you can afford, once. Save the labels. A second student, another size or another recipe, costs only training time.
- Filter with a program. Execution, a schema check or a format check removes broken labels for free. Know what it cannot remove: wrong-but-valid answers pass.
- Hold out gold for the test only. Keep a few hundred human answers to measure the Student; the Teacher's labels cannot measure the Teacher's mistakes.
- Merge the adapter and serve. The merged Student is an ordinary model of 1,004 MB with nothing to load on top.
It fails in three ways. A student is bounded by its teacher on the questions the teacher gets wrong. A hosted teacher can change under you, and the labels you saved then no longer describe it. And outputs from a hosted model may carry terms of use on training other models: read the provider's terms before using an API model's outputs as training data. The teacher here, Qwen2.5-7B-Instruct, and the student are released under Apache-2.0, and the dataset under CC BY 4.0.
The same method extends from answers to actions. Shopify's Sidekick team writes corrected trajectories of a model-driven agent that calls tools in a loop, trains a smaller model on those complete trajectories, reasoning included, and then applies the GRPO of lesson 8 against a judge. Distillation is the supervised stage; reinforcement learning sharpens it.
Next to try, not tested here: a second filter that keeps only labels the Teacher reproduces across two sampled answers, aimed at the wrong-but-valid labels that execution cannot see (the Student copied the Teacher's exact wrong query on 37.9% of its misses).
Next to try, not tested here: more labels (the curve was still rising at 2,946) or a larger Student; the curve cannot say how much each doubling is worth.
Next to try, not tested here: training on the Teacher's probabilities, not its text. Section 5 suggests little is lost on this task, since the Teacher puts a median of 90% on its one answer; on open-ended tasks that may not hold.
12. How it was built
| Item | Setting |
|---|---|
| Teacher | Qwen/Qwen2.5-7B-Instruct, 4-bit NF4 with double quantisation, fp16 compute; 7.6B parameters, 5.44 GB of weights |
| Student | Qwen/Qwen2.5-0.5B-Instruct, fp16, 494M parameters, 0.99 GB |
| Data | sql-create-context at the pinned commit of lesson 3, split by table: 69,170 train, 3,817 validation, 3,923 test. Labelled pool: 3,000 questions drawn at random (seed 42) from train; the gold answers are not used for labelling |
| Test | 500 questions drawn at random (seed 42) from the test split, the same 500 as lessons 4 and 5; metrics: runs in SQLite, exact match after normalisation, 95% interval 1.96·√(p(1−p)/500) |
| Label filter | Keep if non-empty, one statement, starts with SELECT, and runs in SQLite against the question's schema |
| Method | Sequence-level distillation: LoRA SFT of the Student on the Teacher's text. Rank 16, alpha 32, dropout 0.05, target modules all-linear; 8,798,208 trainable parameters (1.75%) |
| Training | 1 epoch; batch 8 with accumulation 2 (effective 16); learning rate 2e-4, cosine decay, warm-up ratio 0.03; fp16; maximum length 256; loss on the answer only; no gradient checkpointing; no validation passes; seed 42. Adapter merged into the fp16 weights before scoring |
| Decoding | Greedy, at most 128 new tokens; batch 16 for scoring, batch 32 for labelling, prompts sorted by length; 12 answers timed one at a time |
| Hardware | Colab Tesla T4, 15.6 GB; transformers 4.51.3, trl 0.19.1, peft 0.15.2, accelerate 1.6.0, datasets 3.6.0, bitsandbytes 0.50.2 |
Time and cost. The Teacher labelled 3,000 questions in 10.1 minutes (604 s, 201 ms per label at batch 32). Training took 1.8 minutes for the 2,946 filtered labels (3,193 padded tokens per second, 6.96 GB peak), 1.9 minutes for the unfiltered 3,000 (7.84 GB) and for the gold-trained Student (7.40 GB), 0.5 minutes for 730 labels (5.80 GB) and 0.9 minutes for 1,471 (6.30 GB). Every adapter is 35.2 MB; the merged Student is 1,004 MB and the label file 0.76 MB. Per answer at batch 16 the Student takes 79 ms and the Teacher 388 ms; one request alone takes 646 ms and 1,303 ms. Serving peak memory is 1.12 GB and 6.01 GB. Every accuracy number comes from the same 500 test questions; the probability measurements in sections 5 and 8 use 64 of them (1,598 answer positions).
Run it yourself
The notebook runs on a free Colab T4. The measured parts are 10.1 minutes of teacher labelling and 7.0 minutes of training across five students (1.8, 1.9, 1.9, 0.5 and 0.9), plus the 15 GB teacher download and scoring seven systems on 500 questions. Every size is one constant in the second code cell. The notebook's sections follow the page: section 1 is the gap, 2 and 3 are the labels, 4 is one answer for a distribution, 5 is the student with the filter and the curve, 6 is the probabilities and the cost, 7 is what the student inherits, and 8 is what to keep. Three changes to try:
- Set
N_LABEL = 6000. The curve in section 7 was still rising at 2,946 labels. Does exact match move beyond one interval, and how much longer does the teacher take to label? - Set
STUDENT_ID = "Qwen/Qwen2.5-1.5B-Instruct", a one-line change that takes about three times as long to train. Lesson 4 measured this model at 58.4% zero-shot and 71.8% on gold labels. How much of the teacher's 65.2% does it recover? - Add a second filter that keeps only labels where the teacher agrees with itself across two sampled answers. It removes wrong-but-valid labels the execution check cannot see. Do the answers at the top of section 9, where the teacher is wrong, change?
Lesson 10 turns from tasks to text: continued pretraining, for a domain the base model reads badly.
How is this page?
Last updated on