Suryanand/ Bootcamp
suryanand.com ↗Let's talk
← Fine-tuningAI guideAdvanced#fine-tuning#distillation#small-models#cost
Frame · ai-engineering / fine-tuning / 07-distillation-into-small-models.mdGuide 078 / 103

Distillation into small models

Distillation is the move you make when a frontier model does your task well but costs too much, runs too slowly, or cannot be deployed where you need it. You use the big model as a teacher, generate a dataset of its behaviour on your task, and train a small student to reproduce it. Done well, a model a fraction of the size handles the bulk of your traffic and you keep the big model for the hard cases.

Why it matters

Small models are now genuinely capable when they are narrow. The DeepSeek-R1 report, for example, released a family of small dense models produced by fine-tuning on reasoning traces generated by the large R1 model, and showed that distillation transferred reasoning ability more effectively than running RL directly on the small models. Most open model families now ship small variants that were trained with some form of distillation from larger siblings.

For product teams the motivations are concrete: latency budgets for voice or autocomplete, per-call cost at high volume, on-device or on-premises deployment for privacy, and independence from a hosted provider's model lifecycle.

How it works

There are three flavours, in increasing order of effort and fidelity.

  1. Sequence-level (response) distillation. The teacher generates outputs for a large set of task prompts; the student is trained on them with ordinary SFT. This is by far the most common, and it works with API-only teachers.
  2. Logit (token-level) distillation. The student is trained to match the teacher's full next-token probability distribution, usually with a KL-divergence loss. This carries more information per token but requires access to teacher logits and a shared tokenizer, so it is typically used within one model family.
  3. On-policy distillation. The student generates, and the teacher scores or provides target distributions on the student's own outputs. This corrects the mismatch where a student trained only on teacher text never learns to recover from its own mistakes. TRL implements this as GKDTrainer, currently under trl.experimental.gkd, where an lmbda setting controls the fraction of student-generated sequences and beta interpolates between forward and reverse KL.
Rendering diagram…

The quality ceiling is set by your prompt set. A student only learns the teacher's behaviour on inputs it saw, so the prompt pool must cover the real distribution, including the awkward edge cases.

Reference architecture

The production pattern I recommend is a cascade: the student handles requests it is confident about, and falls back to the teacher otherwise. Fallback traffic is logged and becomes the next round of distillation data.

Rendering diagram…

Confidence can be a validator (schema check, unit test, constraint check), a classifier on the input, or the student's own token probabilities. Measure the fallback rate; it is your best single metric for how well distillation is going, and it directly maps to cost.

Code

Sequence-level distillation in two steps: generate teacher outputs with a verifier filter, then train the student with TRL's SFTTrainer (see supervised fine-tuning). Here the teacher is called through an OpenAI-compatible API, which many providers and self-hosted servers expose.

import json
from openai import OpenAI
from jsonschema import validate, ValidationError

teacher = OpenAI()  # or OpenAI(base_url=..., api_key=...) for another provider
schema = json.load(open("triage_schema.json"))
SYSTEM = "Return triage JSON for the ticket. Follow the schema exactly."

def teacher_label(ticket: str) -> str | None:
    resp = teacher.responses.create(
        model="gpt-5.5",
        instructions=SYSTEM,
        input=ticket,
    )
    text = resp.output_text
    try:
        validate(json.loads(text), schema)   # verifier: keep only valid outputs
        return text
    except (json.JSONDecodeError, ValidationError):
        return None

with open("tickets.jsonl") as src, open("distill_sft.jsonl", "w") as out:
    for line in src:
        ticket = json.loads(line)["text"]
        label = teacher_label(ticket)
        if label:
            out.write(json.dumps({
                "prompt": [{"role": "system", "content": SYSTEM},
                           {"role": "user", "content": ticket}],
                "completion": [{"role": "assistant", "content": label}],
                "source": "teacher:gpt-5.5",
            }) + "\n")

Then train a 1B to 4B student on distill_sft.jsonl with LoRA, and evaluate it against the teacher on a held-out set.

Trade-offs and pitfalls

  • Terms of service. Many providers prohibit using outputs to build competing models. Read the teacher's terms and get sign-off before you generate at scale.
  • Students inherit teacher errors. Verify outputs wherever you can; a filtered smaller dataset beats an unfiltered large one.
  • Exposure bias. Students trained purely on teacher text can derail on their own mistakes. On-policy distillation or a little RL afterwards helps.
  • Coverage gaps. If the prompt set misses a category, the student will fail silently there. Cluster production inputs and check every cluster is represented.
  • Reasoning traces are long. Distilling chain-of-thought makes training examples and inference outputs much longer; decide whether the student needs to show its work or only the answer.
  • The teacher keeps moving. When the teacher model is upgraded, your student is now distilled from an older version. Budget for periodic refreshes.

Checklist

  • Confirm the teacher's terms allow training on its outputs.
  • Build a prompt pool that covers your real traffic, clustered and balanced.
  • Verify or filter teacher outputs before training.
  • Start with sequence-level distillation; consider on-policy methods if the student derails.
  • Deploy as a cascade with a measurable fallback rate.
  • Evaluate student versus teacher on the same held-out set.

Further reading

Why this exists README

I learn best by explaining things, so I record the explanations. Everything here is free, with no sign-up. If a lesson helps you ship something, I'd love to hear about it.