Model distillation trains a small “student” model on the outputs of a large “teacher,” and the rules around it tightened this month. On November 20, 2026, OpenAI published a post on combatting adversarial distillation, and coverage of the disclosure reported that adaptive extraction attacks against GPT-6.2 Astra dropped from a 54.0% success rate against GPT-6 Astra to 0.2%. If you plan to copy a frontier model’s behavior into something cheaper, the how and the whether now matter equally.
This tutorial builds a working model distillation pipeline in 12 steps. You will label a pool of support tickets with a teacher, filter the labels for quality, fine-tune a small student with LoRA, and test the result against a human-labeled gold set. By the end you will know whether the student can replace the teacher on your task, and what it saves per month. Budget about 90 minutes, plus training time on your GPU.
Don't miss new tech stories on Google
Add Shattered once in the Google app and our stories show up in your news suggestions.
What Model Distillation Does and When It Pays Off #
Distillation moves behavior, not weights. The teacher answers many prompts, you keep the answers worth keeping, and the student learns to imitate them. The TinyBERT authors put the idea plainly: knowledge distillation transfers what a large teacher network knows to a small student network, which is trained to reproduce the behaviors of the teacher, according to Xiaoqi Jiao and co-authors.
The classic proof point predates today’s chat models. Hugging Face’s summary of DistilBERT calls it the first large-scale application of knowledge distillation to pretrained Transformers, with a result of “40% smaller, 60% faster, retaining 97% of BERT’s performance.” Those figures come from a 2019 encoder model, so read them as the shape of the trade and not a promise for your task. Modern generative distillation usually gives up a few accuracy points in return for a model that fits on one GPU.
Distillation pays off under four conditions. The task is narrow and repeated, such as ticket routing, extraction, or tagging. Volume is high enough that per-token fees add up. Latency matters, so a 2B-parameter student answering in 80 milliseconds beats a hosted call at 900. And you can hold out a few hundred human-labeled examples to prove the student works. If any of those is missing, a cheaper hosted model or a better prompt may be the smarter move.
Hard labels, soft labels, and rationales
There are three common ways to pass knowledge down. Hard-label distillation keeps only the teacher’s final answer. Rationale distillation also keeps a short explanation, which gives the student more signal per example. Soft-label distillation uses the teacher’s full probability distribution over tokens, which needs logit access and therefore an open-weight teacher you host yourself. The main path here uses hard labels plus rationales, and Step 9 adds a soft-label option.
| Method | What the student sees | Teacher access needed | Typical use |
|---|---|---|---|
| Hard-label SFT | Final answer only | Any text API | Classification, routing, tagging |
| Rationale SFT | Answer plus short reason | Any text API | Tasks where reasoning helps a small model |
| Soft-label (logit) KD | Full token probabilities | Self-hosted open weights | Squeezing out the last accuracy points |
| Preference distillation | Ranked answer pairs | Any text API plus a judge | Style and tone alignment |
Pick the cheapest row that clears your quality bar. Hard labels with rationales usually land within a few points of the teacher on narrow tasks, and the extra machinery of logit matching is rarely the first thing worth trying.
Check the Rules Before You Generate a Single Label #
Legal and contractual limits decide which teachers you can use, so settle that before spending a dollar. OpenAI’s November 20 statement defines the threat as unauthorized training of another model on a frontier model’s outputs, and says it investigates detected campaigns and enforces against the responsible account networks when they violate its policies or terms of service. The practical reading is simple. Copying a hosted model’s outputs at scale into a model you train is what those terms are written to stop.
The technical side moved too. OpenAI said GPT-6.2 Astra and GPT-6.2 Sol tie protected reasoning to the conversation history that produced it, which makes straightforward extraction of reasoning traces harder. Separately, a report says NIST circulated an initial public draft, SP 2400-102e2026, on November 23 that defines adversarial distillation as reproducing a model’s capabilities without recovering its parameters. It is a draft and not a standard, so watch it rather than cite it as settled.
None of this makes distillation illegal. It makes the teacher choice a compliance decision. We found no official OpenAI statement that documents or permits using GPT-6.2 Astra or Sol as teachers for synthetic-label generation or student training, so do not assume one exists. Read the current terms for whichever provider you use, and keep a dated copy of the version you read.
| Teacher source | Typical status | What to do first |
|---|---|---|
| Open-weight model, permissive license | Usually fine for training other models | Read the license for output-use and naming clauses |
| Open-weight model, custom license | Varies by clause | Check limits on commercial use and derivative models |
| Hosted frontier API | Often restricted | Read the terms of service and get written confirmation |
| Your own earlier production model | Yours to use | Confirm no third-party data limits on its outputs |
| Human annotators | Fully clean | Budget the time, since this is the slow path |
The code below talks to any OpenAI-compatible endpoint, so you can point it at a self-hosted open-weight teacher served by vLLM or Ollama. Our best open-source LLM roundup is a reasonable place to shortlist teachers, and the model card’s license is the final word. For wider context, the AI and machine learning section tracks new releases as they land.
Prerequisites and Versions for the Distillation Pipeline #
You need a Linux or Windows WSL2 machine with an NVIDIA GPU for the training step. A 16 GB card handles a 1B to 3B student with 4-bit , and 24 GB leaves room to breathe. Labeling runs on CPU, because the heavy lifting happens at the teacher endpoint. Record exact package versions with pip freeze after install, since the training stack changes fast and a silent upgrade is a common source of “it worked last week” bugs.
| Component | Requirement | Why it matters |
|---|---|---|
| Python | Not listed | Type hints and tomllib used below |
| PyTorch | 2.x with CUDA 12.x build | Training backend |
| transformers, peft, trl, datasets | Latest release, pinned after install | Model , LoRA adapters, SFT trainer |
| openai (Python client) | Latest release | Talks to any OpenAI-compatible endpoint |
| scikit-learn | Latest release | F1, confusion matrix, Cohen’s kappa |
| GPU | NVIDIA, 16 GB VRAM minimum | LoRA training of a 1B to 3B student |
| Teacher endpoint | OpenAI-compatible URL and key | Self-hosted vLLM or Ollama, or a provider whose terms allow it |
| Disk | 30 GB free | Weights, checkpoints, merged model |
You also need two things no package installs. One is a pool of real, unlabeled text from your own domain, ideally 10,000 to 30,000 examples. The other is a few hundred examples labeled by people who know the task. The second one is the part teams skip, and it is the only thing that tells you whether the whole exercise worked.
Step 1: Define the Task and the Pass Line #
Write the success criteria before you write any code. Vague goals produce students that look fine in a demo and fail in production. For this project the task is support-ticket triage: read a customer message, return one of six labels, and add a one-sentence reason. The labels are billing, bug, how_to, account_access, feature_request, and other.
Set three pass conditions now and write them down. First, student macro-F1 on the gold set must land within 3 points of the teacher’s macro-F1. Second, no single label may drop more than 8 points of recall against the teacher. Third, median latency must beat the teacher’s by at least 5x on your hardware. These numbers are placeholders you should tune, but picking them in advance stops you from rationalizing a mediocre result later.
Hamel Husain, a machine learning engineer who writes widely on evaluation, makes the point bluntly about automated judges, and it applies equally to a distilled student: the only way to trust a black box is to check it against ground truth. Your gold set is that ground truth.
Step 2: Create the Project and Install Dependencies #
Create a clean folder and a virtual environment. Keep data, code, and outputs in separate directories so you can delete a bad run without touching your gold labels.
mkdir distill-triage && cd distill-triage
python3.12 -m venv .venv && source .venv/bin/activate
mkdir -p data runs scripts
pip install --upgrade pip
pip install torch transformers peft trl datasets accelerate bitsandbytes openai scikit-learn tqdm
pip freeze > runs/requirements.lock.txt
python -c "import torch; print(torch.__version__, torch.cuda.is_available())"
The last line should print a PyTorch version followed by True. If it prints False, fix the CUDA install now. Everything after Step 7 depends on it.
2.x.x True
Next, put your settings in one file so the scripts never hard-code a model name or an endpoint. The teacher and student identifiers come from environment variables, which keeps this tutorial valid when you swap models next month.
import os
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
DATA = ROOT / "data"
RUNS = ROOT / "runs"
LABELS = ["billing", "bug", "how_to", "account_access", "feature_request", "other"]
TEACHER_BASE_URL = os.environ.get("TEACHER_BASE_URL", "http://localhost:8000/v1")
TEACHER_API_KEY = os.environ.get("TEACHER_API_KEY", "not-needed-for-local")
TEACHER_MODEL = os.environ["TEACHER_MODEL"] # e.g. the id your server exposes
STUDENT_MODEL = os.environ["STUDENT_MODEL"] # a small open-weight instruct model you may fine-tune
SEED = 1234
VOTES = 3 # teacher samples per ticket for the consistency filter
TEMPERATURE = 0.7 # sampling temperature for the voting runs
Step 3: Build the Unlabeled Pool and the Gold Set #
Export your tickets as a JSON Lines file with one object per line and an id and text field. Strip names, emails, phone numbers, and order IDs before the text leaves your systems. A distillation dataset is a copy of your customers’ words, and it will end up in a training run, a checkpoint, and probably a backup.
Then split off the gold set first, before any teacher sees the pool. Pull 400 tickets at random, stratified if your label mix is lopsided, and have two people label them independently. Where they disagree, a third person decides. The gold set never enters training. If it does, every number you report afterward is inflated.
import json, random
from config import DATA, SEED
rows = [json.loads(l) for l in open(DATA / "tickets_raw.jsonl", encoding="utf-8")]
random.Random(SEED).shuffle(rows)
gold_to_label = rows[:400]
pool = rows[400:]
with open(DATA / "gold_unlabeled.jsonl", "w", encoding="utf-8") as f:
for r in gold_to_label:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
with open(DATA / "pool.jsonl", "w", encoding="utf-8") as f:
for r in pool:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
print(f"gold to label: {len(gold_to_label)} pool: {len(pool)}")
gold to label: 400 pool: 19600
After your annotators finish, save the result as data/gold.jsonl with id, text, and label fields. Compute their agreement with Cohen’s kappa before trusting it. If two trained humans only reach a kappa of 0.6, your label definitions are fuzzy, and no student will beat that ceiling.
Common pitfall: splitting after labeling. If the teacher labels the whole export and you carve out a gold set afterward, near-duplicate tickets will sit on both sides of the split. Deduplicate on normalized text before the split, not after.
Step 4: Write the Teacher Client and the Labeling Prompt #
The teacher needs a prompt that produces machine-readable output every time. Ask for JSON with exactly two keys, label and reason, and validate the response in code instead of hoping. Keep the reason to one sentence. Long rationales cost output tokens and teach the student to ramble.
import json, time
from openai import OpenAI
from config import (TEACHER_BASE_URL, TEACHER_API_KEY, TEACHER_MODEL,
LABELS, TEMPERATURE)
client = OpenAI(base_url=TEACHER_BASE_URL, api_key=TEACHER_API_KEY)
SYSTEM = (
"You triage customer support tickets. Choose exactly one label from: "
+ ", ".join(LABELS)
+ ". Definitions: billing = charges, invoices, refunds, plans. "
"bug = something is broken or behaves wrongly. "
"how_to = the user asks how to do something that works. "
"account_access = login, password, 2FA, locked accounts. "
"feature_request = the user wants something that does not exist. "
"other = anything else. "
"Reply with JSON only: {\"label\": \"...\", \"reason\": \"one short sentence\"}."
)
def ask(text, temperature=TEMPERATURE, retries=3):
for attempt in range(retries):
try:
resp = client.chat.completions.create(
model=TEACHER_MODEL,
temperature=temperature,
messages=[{"role": "system", "content": SYSTEM},
{"role": "user", "content": text}],
max_tokens=120,
)
raw = resp.choices[0].message.content.strip()
raw = raw.removeprefix("``` json").removesuffix("```").strip()
obj = json.loads(raw)
if obj.get("label") in LABELS and isinstance(obj.get("reason"), str):
return {"label": obj["label"], "reason": obj["reason"].strip()}
except Exception:
time.sleep(2 ** attempt)
return None
Test it on one ticket before you launch 20,000 calls. A bad system prompt is cheap to fix now and expensive to fix after the run.
python -c "
from teacher import ask
print(ask('I was charged twice for March and nobody answered my email.'))
"
{'label': 'billing', 'reason': 'The customer reports a duplicate charge and wants it resolved.'}
Step 5: Label the Pool With Resumable Voting Runs #
Call the teacher three times per ticket at a moderate temperature. Three samples cost three times as much as one, but they give you a free quality signal in the next step. Write results to disk as you go, and skip IDs that already exist, so a crash at ticket 14,000 costs you a minute and not an afternoon.
import json, sys
from concurrent.futures import ThreadPoolExecutor
from tqdm import tqdm
from config import DATA, VOTES
from teacher import ask
src = DATA / (sys.argv[1] if len(sys.argv) > 1 else "pool.jsonl")
dst = DATA / (sys.argv[2] if len(sys.argv) > 2 else "pool_votes.jsonl")
done = set()
if dst.exists():
done = {json.loads(l)["id"] for l in open(dst, encoding="utf-8")}
rows = [json.loads(l) for l in open(src, encoding="utf-8")]
todo = [r for r in rows if r["id"] not in done]
print(f"{len(todo)} tickets to label, {len(done)} already done")
def work(r):
votes = [ask(r["text"]) for _ in range(VOTES)]
return {"id": r["id"], "text": r["text"], "votes": votes}
with open(dst, "a", encoding="utf-8") as out, ThreadPoolExecutor(max_workers=16) as ex:
for res in tqdm(ex.map(work, todo), total=len(todo)):
out.write(json.dumps(res, ensure_ascii=False) + "\n")
out.flush()
Run it twice, once for the pool and once for the unlabeled gold tickets so you can score the teacher too. The second run is small and tells you how good your teacher really is on your data.
python scripts/label_pool.py gold.jsonl gold_votes.jsonl
python scripts/label_pool.py pool.jsonl pool_votes.jsonl
19600 tickets to label, 0 already done
100%|##########| 19600/19600 [41:12<00:00, 7.93it/s]
Your throughput depends on the endpoint, so treat the timing above as an example. Watch the error rate in the first minute. If more than a few percent of votes come back None, stop and fix the prompt or the max_tokens setting before burning more of your quota.
Step 6: Filter Teacher Labels With Self-Consistency #
A teacher is wrong sometimes, and the student will faithfully learn its mistakes. Self-consistency catches many of them. If all three votes agree, the label is probably stable. If they split, the ticket is either ambiguous or the teacher is guessing, and the student gains little from seeing it.
import json
from collections import Counter
from config import DATA
kept, dropped, split = [], 0, 0
for line in open(DATA / "pool_votes.jsonl", encoding="utf-8"):
r = json.loads(line)
votes = [v for v in r["votes"] if v]
if len(votes) < 3:
dropped += 1
continue
counts = Counter(v["label"] for v in votes)
label, n = counts.most_common(1)[0]
if n == 3:
reason = next(v["reason"] for v in votes if v["label"] == label)
kept.append({"id": r["id"], "text": r["text"], "label": label,
"reason": reason, "agreement": 1.0})
else:
split += 1
with open(DATA / "pool_filtered.jsonl", "w", encoding="utf-8") as f:
for r in kept:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
print(f"kept {len(kept)} split-vote {split} invalid {dropped}")
print(Counter(r["label"] for r in kept).most_common())
kept 16810 split-vote 2392 invalid 398
[('how_to', 5120), ('bug', 4388), ('billing', 3012), ('account_access', 2204), ('feature_request', 1360), ('other', 726)]
Those counts are an illustration, and yours will differ. What matters is the shape. Unanimous filtering tends to remove rare and ambiguous classes first, so a rare label can shrink below the point where the student learns it. The next step deals with that. Also keep the split-vote tickets in a separate file. They are your best candidates for human review, and they often reveal a label definition that needs tightening.
Step 7: Assemble a Balanced Training Set in Chat Format #
Convert the filtered rows into the chat format the student’s tokenizer expects. Cap the biggest classes so a flood of easy how_to tickets does not drown the rare ones, and keep a small validation slice for early stopping. The assistant message is the same JSON the teacher produced, so the student learns the exact output contract your application will parse.
import json, random
from collections import defaultdict
from config import DATA, SEED
from teacher import SYSTEM
CAP = 1500 # max examples per label
rows = [json.loads(l) for l in open(DATA / "pool_filtered.jsonl", encoding="utf-8")]
by_label = defaultdict(list)
for r in rows:
by_label[r["label"]].append(r)
rng = random.Random(SEED)
chosen = []
for label, items in by_label.items():
rng.shuffle(items)
chosen.extend(items[:CAP])
rng.shuffle(chosen)
def to_chat(r):
answer = json.dumps({"label": r["label"], "reason": r["reason"]}, ensure_ascii=False)
return {"messages": [
{"role": "system", "content": SYSTEM},
{"role": "user", "content": r["text"]},
{"role": "assistant", "content": answer},
]}
val_n = max(200, len(chosen) // 20)
val, train = chosen[:val_n], chosen[val_n:]
for name, part in (("train", train), ("val", val)):
with open(DATA / f"sft_{name}.jsonl", "w", encoding="utf-8") as f:
for r in part:
f.write(json.dumps(to_chat(r), ensure_ascii=False) + "\n")
print(f"train {len(train)} val {len(val)}")
train 6894 val 345
Common pitfall: training on the long system prompt in every example wastes tokens and time. It is fine for a first run, and once the student works you can shorten it to a single line and retrain. Whatever you pick, use the identical system prompt at inference, or accuracy will drop for reasons that look mysterious.
Step 8: Fine-Tune the Student With LoRA #
LoRA trains small adapter matrices and leaves the base weights frozen, so a 1B to 3B student fits on a single consumer GPU when you load it in 4-bit. The script below uses TRL’s supervised trainer on the chat-formatted files from Step 7. TRL renames arguments between releases, so if a keyword raises a TypeError, check the docs for the version you pinned in Step 2.
import torch
from datasets import load_dataset
from peft import LoraConfig
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
from trl import SFTConfig, SFTTrainer
from config import DATA, RUNS, STUDENT_MODEL, SEED
tok = AutoTokenizer.from_pretrained(STUDENT_MODEL)
if tok.pad_token is None:
tok.pad_token = tok.eos_token
bnb = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16,
)
model = AutoModelForCausalLM.from_pretrained(
STUDENT_MODEL, quantization_config=bnb, device_map="auto"
)
lora = LoraConfig(
r=16, lora_alpha=32, lora_dropout=0.05,
target_modules="all-linear", task_type="CAUSAL_LM",
)
ds = load_dataset("json", data_files={
"train": str(DATA / "sft_train.jsonl"),
"val": str(DATA / "sft_val.jsonl"),
})
cfg = SFTConfig(
output_dir=str(RUNS / "student_lora"),
num_train_epochs=2,
per_device_train_batch_size=4,
gradient_accumulation_steps=8,
learning_rate=2e-4,
lr_scheduler_type="cosine",
warmup_ratio=0.03,
logging_steps=20,
eval_strategy="steps",
eval_steps=100,
save_strategy="steps",
save_steps=100,
save_total_limit=2,
load_best_model_at_end=True,
bf16=True,
max_length=1024,
seed=SEED,
report_to="none",
)
trainer = SFTTrainer(
model=model,
args=cfg,
train_dataset=ds["train"],
eval_dataset=ds["val"],
processing_class=tok,
peft_config=lora,
)
trainer.train()
trainer.save_model(str(RUNS / "student_lora" / "final"))
print("saved adapter")
{'loss': 1.12, 'epoch': 0.06}
{'loss': 0.41, 'epoch': 0.58}
{'eval_loss': 0.29, 'epoch': 0.58}
{'loss': 0.27, 'epoch': 1.62}
{'eval_loss': 0.25, 'epoch': 1.62}
saved adapter
Those loss values are placeholders that show the expected pattern: a quick drop, then a slow flattening. Watch the gap between training and validation loss. If validation loss climbs while training loss keeps falling, the student is memorizing your pool, and you should cut epochs or add data.
Step 9: Add Soft Labels When You Self-Host the Teacher #
Skip this step if the teacher sits behind an API. It only works when you can read the teacher’s logits and the student shares its tokenizer, which in practice means two models from one family at different sizes. The idea is to blend the usual cross-entropy loss with a KL-divergence term that pulls the student’s token distribution toward the teacher’s, softened by a temperature.
import torch
import torch.nn.functional as F
def distill_loss(student_logits, teacher_logits, labels, T=2.0, alpha=0.5):
"""Blend hard-label cross-entropy with soft-label KL divergence."""
vocab = student_logits.size(-1)
ce = F.cross_entropy(
student_logits.view(-1, vocab), labels.view(-1), ignore_index=-100
)
mask = (labels != -100).unsqueeze(-1)
s = F.log_softmax(student_logits / T, dim=-1)
t = F.softmax(teacher_logits / T, dim=-1)
kl = F.kl_div(s, t, reduction="none") * mask
kl = kl.sum() / mask.sum().clamp(min=1) * (T * T)
return alpha * ce + (1 - alpha) * kl
Plug this into a subclassed trainer’s compute_loss, run the teacher in eval mode under torch.no_grad(), and make sure both models see identical token IDs. Teacher logits for a large model eat memory fast, which is why many teams precompute and store only the top 20 or so probabilities per position. Treat soft labels as a second-round upgrade. Get the hard-label pipeline working and measured first.
Step 10: Evaluate the Student Against the Human Gold Set #
This is the step that decides everything. Run the student on the 400 gold tickets with greedy decoding, parse its JSON, and compare against the human labels. Run the same scoring on the teacher’s majority vote from gold_votes.jsonl. Report macro-F1, per-label recall, Cohen’s kappa against the humans, and the share of outputs that failed to parse.
import json, sys, torch
from collections import Counter
from peft import PeftModel
from sklearn.metrics import f1_score, recall_score, cohen_kappa_score
from transformers import AutoModelForCausalLM, AutoTokenizer
from config import DATA, RUNS, STUDENT_MODEL, LABELS
from teacher import SYSTEM
gold = [json.loads(l) for l in open(DATA / "gold.jsonl", encoding="utf-8")]
y_true = [g["label"] for g in gold]
votes = {}
for l in open(DATA / "gold_votes.jsonl", encoding="utf-8"):
r = json.loads(l)
labs = [v["label"] for v in r["votes"] if v]
votes[r["id"]] = Counter(labs).most_common(1)[0][0] if labs else "other"
y_teacher = [votes.get(g["id"], "other") for g in gold]
tok = AutoTokenizer.from_pretrained(STUDENT_MODEL)
base = AutoModelForCausalLM.from_pretrained(STUDENT_MODEL, torch_dtype=torch.bfloat16, device_map="auto")
model = PeftModel.from_pretrained(base, str(RUNS / "student_lora" / "final")).eval()
y_student, bad = [], 0
for g in gold:
msgs = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": g["text"]}]
ids = tok.apply_chat_template(msgs, add_generation_prompt=True, return_tensors="pt").to(model.device)
with torch.no_grad():
out = model.generate(ids, max_new_tokens=100, do_sample=False)
text = tok.decode(out[0][ids.shape[-1]:], skip_special_tokens=True)
try:
label = json.loads(text)["label"]
if label not in LABELS:
raise ValueError
except Exception:
label, bad = "other", bad + 1
y_student.append(label)
def report(name, pred):
print(f"{name}: macroF1={f1_score(y_true, pred, labels=LABELS, average='macro'):.3f} "
f"kappa={cohen_kappa_score(y_true, pred):.3f}")
rec = recall_score(y_true, pred, labels=LABELS, average=None, zero_division=0)
print(" recall:", {l: round(float(r), 2) for l, r in zip(LABELS, rec)})
report("teacher", y_teacher)
report("student", y_student)
print(f"student parse failures: {bad}/{len(gold)}")
json.dump({
"teacher_macro_f1": round(f1_score(y_true, y_teacher, labels=LABELS, average="macro"), 4),
"gold_macro_f1": round(f1_score(y_true, y_student, labels=LABELS, average="macro"), 4),
}, open(RUNS / "scores.json", "w"))
teacher: macroF1=0.874 kappa=0.842
recall: {'billing': 0.93, 'bug': 0.89, 'how_to': 0.91, 'account_access': 0.90, 'feature_request': 0.81, 'other': 0.70}
student: macroF1=0.851 kappa=0.819
recall: {'billing': 0.92, 'bug': 0.87, 'how_to': 0.90, 'account_access': 0.88, 'feature_request': 0.76, 'other': 0.64}
student parse failures: 3/400
The numbers above are a made-up illustration of what a passing run looks like, so do not compare your result to them. Compare it to the pass line from Step 1. In this example the student sits 2.3 points of macro-F1 below the teacher, inside the 3-point budget. The other label lost 6 points of recall, inside the 8-point limit but worth a look.
Do not stop at the headline score. Husain’s warning applies here as well: an automated judge, and by extension a distilled model, is only as good as its correlation with your actual users and domain experts. Read 30 student errors by hand. Look for patterns, such as sarcasm, mixed-topic tickets, or non-English messages, because those clusters tell you what to add to the next training round.
Step 11: Run the Cost and Latency Break-Even Math #
A student that passes quality can still lose on money. Compute the break-even before you promise anyone savings. The model is simple: a one-time cost for labeling, training, and engineering, against a monthly saving equal to the teacher bill minus the cost of serving the student.
To make the arithmetic concrete, assume a workload of 200,000 tickets a month, with each call using 400 input tokens (system prompt included) and 60 output tokens. Those are assumptions for the example, so replace them with your own logs. The prices below are OpenAI’s list rates per million tokens as shown in its pricing materials around November 21 to 24, 2026: GPT-6.2 Astra at $8 input and $40 output, GPT-6.2 Sol at $2 and $10, and GPT-6 Luna at $0.10 and $0.50. Hosted rates change often, and promotional rates such as GPT-5.6 Sol’s, which was listed through November 30, 2026, do not apply here.
PRICES = { # USD per 1M tokens: (input, output), from the provider pricing page
"GPT-6.2 Astra": (8.00, 40.00),
"GPT-6.2 Sol": (2.00, 10.00),
"GPT-6 Luna": (0.10, 0.50),
}
TICKETS_PER_MONTH = 200_000
IN_TOK, OUT_TOK = 400, 60
LABEL_CALLS = 19_600 * 3 # pool size x votes
def monthly(price):
i, o = price
return TICKETS_PER_MONTH * (IN_TOK * i + OUT_TOK * o) / 1e6
def one_time_labeling(price):
i, o = price
return LABEL_CALLS * (IN_TOK * i + OUT_TOK * o) / 1e6
STUDENT_SERVING_PER_MONTH = 400.0 # ASSUMPTION: your GPU box or rental, per month
for name, p in PRICES.items():
m, one = monthly(p), one_time_labeling(p)
saving = m - STUDENT_SERVING_PER_MONTH
verdict = f"pays back in {one / saving:.1f} months" if saving > 0 else "never pays back"
print(f"{name:14s} monthly ${m:8.2f} label once ${one:7.2f} saving ${saving:8.2f} {verdict}")
bash
GPT-6.2 Astra monthly $ 1120.00 label once $ 329.28 saving $ 720.00 pays back in 0.5 months
GPT-6.2 Sol monthly $ 280.00 label once $ 82.32 saving $ -120.00 never pays back
GPT-6 Luna monthly $ 14.00 label once $ 4.12 saving $ -386.00 never pays back
| Teacher or hosted model | Input / output per 1M tokens | Monthly bill at 200,000 tickets | One-time labeling run |
|---|---|---|---|
| GPT-6.2 Astra | $8 / $40 | Not listed | Not listed |
| GPT-6.2 Sol | $2 / $10 | $280.00 | Not listed |
| GPT-6 Luna | $0.10 / $0.50 | $14.00 | Not listed |
The lesson is uncomfortable and useful. At this volume, distilling from a premium model into a self-hosted student saves money only if you are replacing that premium model in production. Against a budget tier, a $400-a-month GPU loses badly. This is budget math only, and it is not a statement that any of these hosted models may legally serve as a teacher. Step 1 and the terms check still come first.
Latency deserves the same honesty. Time 200 student requests on your actual hardware and compare the median and the 95th percentile to the teacher endpoint you use today. A student that wins on cost but adds a queue under load can still lose on user experience. Capture both numbers in the same run, at the same concurrency, or the comparison means nothing.
Step 12: Merge, Version, and Gate the Student in CI #
Merge the adapter into the base weights so serving does not need PEFT, then write a manifest that records everything someone would need to reproduce or audit the model. Include the teacher identifier, the date you read the teacher’s terms, the system prompt hash, and the gold-set scores. When a regulator, a customer, or a colleague asks where the student’s behavior came from, the manifest answers in one file.
import hashlib, json, datetime, torch
from peft import PeftModel
from transformers import AutoModelForCausalLM, AutoTokenizer
from config import RUNS, STUDENT_MODEL, TEACHER_MODEL
from teacher import SYSTEM
base = AutoModelForCausalLM.from_pretrained(STUDENT_MODEL, torch_dtype=torch.bfloat16)
merged = PeftModel.from_pretrained(base, str(RUNS / "student_lora" / "final")).merge_and_unload()
out = RUNS / "student_merged"
merged.save_pretrained(out)
AutoTokenizer.from_pretrained(STUDENT_MODEL).save_pretrained(out)
manifest = {
"student_base": STUDENT_MODEL,
"teacher": TEACHER_MODEL,
"teacher_terms_read_on": "FILL-IN-DATE",
"system_prompt_sha256": hashlib.sha256(SYSTEM.encode()).hexdigest(),
"built_at": datetime.datetime.now(datetime.timezone.utc).isoformat(),
**json.load(open(RUNS / "scores.json")), # teacher_macro_f1 and gold_macro_f1 from Step 10
}
(out / "manifest.json").write_text(json.dumps(manifest, indent=2))
print("merged model written to", out)
Finally, turn the Step 1 pass line into a gate that fails a build. Retrain whenever the label definitions, the teacher, or the base student changes, and block the release if the score slips.
import json, sys
from config import RUNS
m = json.load(open(RUNS / "student_merged" / "manifest.json"))
teacher_f1, student_f1 = m["teacher_macro_f1"], m["gold_macro_f1"]
if student_f1 is None or student_f1 < teacher_f1 - 0.03:
print(f"FAIL: student {student_f1} vs teacher {teacher_f1} (budget 0.03)")
sys.exit(1)
print("PASS")
The manifest now carries both Step 10 scores, so the gate has what it needs. Serve the merged model with vLLM or convert it for llama.cpp if you want a CPU-friendly build. Whichever you choose, rerun the Step 10 evaluation on the served copy, because quantization and chat-template differences can move scores.
Seven Common Pitfalls That Quietly Ruin a Distilled Model #
- Leaking the gold set into training. Near-duplicate tickets, quoted email threads, and templated auto-replies slip across the split. Deduplicate on normalized text and hash the gold IDs into a blocklist that the training script checks.
- Trusting the teacher blindly. A teacher with 87% accuracy on your data teaches the student its 13% of mistakes. Score the teacher on the gold set first, and fix the label definitions if it struggles.
- Skipping the baseline. Before any training, run the untouched student with the same prompt. If the base model already scores close to your pass line, a prompt tweak may beat a training run.
- Overfitting to one phrasing. If every training ticket comes from one product line, the student fails on the next. Sample the pool across products, regions, and months.
- Class collapse after filtering. Unanimous-vote filters remove rare labels first. Check the per-class counts after Step 6 and oversample or relabel the thin classes by hand.
- Changing the prompt between training and serving. A reworded system prompt moves accuracy by several points. Store the prompt hash in the manifest and assert it at startup.
- Ignoring the terms of service. Output from some providers cannot be used to train competing models, and enforcement is real. Keep the dated terms record from Step 12 with the model, and rerun the check when you switch teachers.
Troubleshooting: 9 Problems and Their Fixes #
| Symptom | Likely cause | Fix |
|---|---|---|
torch.cuda.is_available() prints False |
CPU-only wheel installed | Reinstall PyTorch from the CUDA 12.x index and check nvidia-smi |
Many teacher votes return None |
Output cut off or markdown fences | Raise max_tokens , keep the fence stripping, and log raw replies for 20 failures |
| 429 or rate-limit errors during labeling | Too many parallel workers | Lower max_workers , add backoff, and rely on the resumable file |
TypeError on anSFTTrainer orSFTConfig argument |
TRL renamed the keyword in your version | Check the docs for your pinned version, for example processing_class versustokenizer |
| CUDA out of memory in training | Batch or sequence too large | Drop batch size to 2, raise gradient accumulation, cut max_length , enable gradient checkpointing |
| Training loss falls but eval loss rises | Overfitting | Reduce epochs to 1, lower the learning rate to 1e-4, add more varied data |
| Student outputs prose instead of JSON | Chat template mismatch or too few steps | Confirm the same template at train and inference, then check the first 5 training samples decoded |
| Student parse failures above 2% | Rationale too long, truncation | Shorten rationales, raise max_new_tokens , add a constrained-decoding grammar at serving |
| Gold F1 high, production accuracy poor | Gold set not representative | Re-sample gold from recent live traffic and add the hard cases you found in error review |
When an error is not on the list, bisect it. Run Step 8 on 200 examples for 20 steps. If that works, the bug lives in the data volume or a rare malformed row, and a quick scan for empty strings and extremely long texts usually finds it.
Advanced Tips for Better Students #
Mine the disagreements
The split-vote tickets in the Step 6 example are good candidates for human review. Send a few hundred to a human labeler, fold the corrected labels back in, and retrain. In practice, 300 hard, human-verified examples can help the student more than 3,000 more easy ones.
Run the student as a first-pass router
Have the student emit a confidence score from the token probability of its label, and escalate low-confidence tickets to a stronger model or a person. This cascade pattern keeps most traffic on cheap hardware while protecting the hard cases. Calibrate the threshold on the gold set so that escalated tickets contain most of the student’s errors.
Beyond that, consider multi-teacher voting, where two different open-weight teachers must agree before a label enters training. It costs more labeling compute but reduces single-model quirks. Also try shortening the system prompt for the student only after the first successful run, and retest, since fewer prompt tokens cut serving cost on every request. Finally, rerun the whole pipeline on a schedule. Customer language drifts, and a student trained in November will meet new product names by spring.
The Complete Working Project #
Here is the final layout and a single script that runs the pipeline end to end. Set the five environment variables, drop your tickets into data/tickets_raw.jsonl, and your annotated gold file into data/gold.jsonl after the first split.
distill-triage/
data/
tickets_raw.jsonl # your exported, scrubbed tickets
gold.jsonl # human-labeled, never trained on
pool.jsonl, pool_votes.jsonl, pool_filtered.jsonl
sft_train.jsonl, sft_val.jsonl
runs/
requirements.lock.txt
student_lora/final/
student_merged/ # weights + manifest.json
scripts/
config.py teacher.py split_data.py label_pool.py
filter_votes.py build_sft.py train_student.py
kd_loss.py evaluate.py cost_model.py
package_student.py gate.py
bash
#!/usr/bin/env bash
set -euo pipefail
export TEACHER_BASE_URL="http://localhost:8000/v1"
export TEACHER_API_KEY="local"
export TEACHER_MODEL="your-open-weight-teacher-id"
export STUDENT_MODEL="your-small-open-weight-student-id"
source .venv/bin/activate
python scripts/label_pool.py gold_unlabeled.jsonl gold_votes.jsonl
python scripts/label_pool.py pool.jsonl pool_votes.jsonl
python scripts/filter_votes.py
python scripts/build_sft.py
python scripts/train_student.py
python scripts/evaluate.py
python scripts/cost_model.py
python scripts/package_student.py
python scripts/gate.py
kept 16810 split-vote 2392 invalid 398
train 6894 val 345
saved adapter
teacher: macroF1=0.874 kappa=0.842
student: macroF1=0.851 kappa=0.819
student parse failures: 3/400
merged model written to runs/student_merged
PASS
Your output will differ, and a FAIL from the gate is a perfectly good result. It means the pipeline caught a student that was not ready, which is the point of building it.
Frequently Asked Questions About Model Distillation #
What is model distillation in simple terms?
It is training a small model to imitate a large one. The large teacher produces answers, and the student learns from them, ending up faster and cheaper to run at some cost in accuracy.
Is distilling a model from a commercial API allowed?
It depends on the provider’s terms. OpenAI said on November 20, 2026 that it enforces its policies against unauthorized adversarial distillation, and we found no official statement permitting GPT-6.2 Astra or Sol as teachers. Read the current terms, and use an open-weight or in-house teacher when in doubt.
How many examples does distillation need?
For a narrow classification task, start with a modest set of clean, balanced examples. Quality and class balance matter more than raw count, so measure on a gold set and add data only where errors cluster.
What is the difference between distillation and fine-tuning?
Fine-tuning is the training method, and distillation is a source of training data. Here the labels come from a teacher model instead of people, and the actual training step is ordinary LoRA fine-tuning.
Do I need logits from the teacher?
No. Hard labels and short rationales work with any text API and cover most narrow tasks. Logit matching helps only when you host the teacher and share a tokenizer with the student.
How do I know the student is good enough?
Compare it to a human-labeled gold set against a pass line you set before training. Check macro-F1, per-label recall, format failures, and a hand review of errors. If it clears the line, ship it behind the regression gate.
Will distillation always save money?
No. In the worked example, replacing a premium model saved about $720 a month, while replacing a mid-tier or budget model cost more than it saved. Run the Step 11 math with your own volume and serving costs before you build anything.