LLM Knowledge Distillation: Principles, Technical Routes, and Engineering Practices
Knowledge distillation transfers capabilities from a large teacher model to a smaller, lighter student model. This guide explains how distillation works, why organizations use it to cut inference costs and latency while specializing models for specific domains, and how to choose among response-based, feature-based, and relation-based routes. It also walks through distilling open-source models end to end, from building training data through SFT, optional logits distillation, and evaluation, covering suggested parameters, licensing and compliance checks, common failure modes, and a five-point engineering checklist.
What Is Knowledge Distillation
Knowledge distillation trains a smaller model (the Student) to mimic the behavior of a larger model (the Teacher), transferring the larger model’s capabilities into a lighter one. Unlike standard supervised learning, which relies only on ground-truth labels (hard labels), distillation can also use the probability distributions produced by the teacher (soft labels).
Soft labels capture the relative relationships among classes. For example, if a sample has a probability of 0.9 for “cat,” 0.07 for “tiger,” and nearly 0 for “truck,” that distribution carries “dark knowledge” that a single correct label does not. It gives the student a richer supervision signal.
A temperature coefficient T softens the output distribution:
# The example below applies to logits distillation on classification models# with the same vocabulary; for token-level distillation of large language# models, the teacher and student must share a tokenizer, and large-vocabulary# truncation should be taken into account.import torchimport torch.nn.functional as Fdef distillation_loss(student_logits, teacher_logits, labels, T=4.0, alpha=0.7):"""T: temperature; higher values produce a smoother distributionalpha: weight balancing the soft-label loss against the hard-label loss"""soft_loss = F.kl_div(F.log_softmax(student_logits / T, dim=-1),F.softmax(teacher_logits / T, dim=-1),reduction="batchmean",) * (T * T)hard_loss = F.cross_entropy(student_logits, labels)return alpha * soft_loss + (1 - alpha) * hard_loss
Within a reasonable range, a higher temperature produces a smoother distribution that carries more information about non-target classes. This makes it easier for the student to learn fine-grained patterns. The multiplication by T² compensates for the reduction in gradient magnitude caused by the temperature during backpropagation.
Higher is not always better, though. Too high a temperature averages out the soft labels too much and weakens the supervision signal. Too low a temperature keeps the distribution too peaked and limits the benefits of distillation. In practice, tune T per task on the validation set.
Why Organizations Distill LLMs: Cost, Latency, and Domain Specialization
Large models have massive parameter counts. Deploying them directly can mean high inference costs, high latency, and demanding hardware requirements. Knowledge distillation offers higher efficiency in exchange for a controlled loss in accuracy:
- Lower inference costs: A distilled lightweight model can reduce memory usage and compute per call. The exact reduction depends on the teacher and student model sizes, training data, inference hardware, and quantization strategy.
- Faster responses: Small models generally achieve higher throughput and lower latency on the same hardware, making them better suited to high-concurrency online services.
- Edge and private deployments: Distilled models can run on resource-constrained devices or in private environments. This helps meet compliance needs such as data residency requirements.
- Domain specialization: Distilling and fine-tuning on vertical-domain data lets a small model approach the teacher’s performance on specific tasks. This combines broad general capabilities with stronger domain expertise.
How does distillation differ from fine-tuning? Fine-tuning typically updates model parameters directly using human-labeled or instruction data so the model learns to produce the desired outputs. Distillation places more emphasis on the teacher’s output distributions, generated responses, or token-level probabilities, so the student can mimic the teacher’s behavior. The two are often combined: first use the teacher to generate data, then run SFT on the student, and finally add soft-label or logits distillation.
The Three Technical Routes of Knowledge Distillation and How to Choose
Distillation is commonly divided into three categories, based on how much information the student can access:
- Response-based: The student imitates the teacher’s final output. In classification tasks, the teacher’s output can be probabilities or logits. In generation tasks, it can be text or token-level logprobs. This approach is the easiest to implement.
- Feature-based: The student imitates the teacher’s intermediate hidden representations. This provides a richer supervision signal, but requires visibility into the teacher’s internal structure.
- Relation-based: The student imitates the relationships among samples, such as distances between same-class samples or contrastive relationships. It is well suited to structured tasks and retrieval tasks.
In engineering practice, it is also important to distinguish between black-box and white-box distillation. Black-box distillation typically gives the student access only to inputs and outputs, not the teacher’s weights, gradients, or intermediate layers. Whether teacher probabilities are available depends on whether the API returns logprobs. White-box distillation allows access to the teacher’s full outputs and even intermediate representations. Whether gradients can be accessed depends on training-framework-level access.
| Technical Route | Information Required | Implementation Difficulty | Typical Use Cases |
|---|---|---|---|
| Response-based | Teacher outputs, probabilities, logprobs | Low | Classification, generation, API output distillation |
| Feature-based | Intermediate layer representations | Medium | White-box model compression, retrieval models |
| Relation-based | Sample relationship structure | Medium–High | Ranking, retrieval, structured tasks |
Selection guidelines:
- If you can only access a closed API, prioritize response-based distillation.
- If you can access the teacher’s intermediate layers, consider feature-based distillation.
- If the task emphasizes relationships among samples, relation-based distillation may be a good fit.
How to Distill and Further Develop Open-Source Models
When using an open-source large model as the teacher, or continuing to optimize an open-source small model, the workflow typically follows these steps:
- Data construction: Use the teacher to generate responses to domain-specific instructions, forming instruction–response pairs. Data quality sets the upper bound on distillation results. Be sure to deduplicate, remove noise, and filter out low-quality responses. Before ingesting the data, remove and de-identify sensitive content, such as personal information and account credentials.
- Supervised fine-tuning (SFT): Use this data to run instruction fine-tuning on the student, so it initially aligns with the teacher’s style and task format.
- Preference alignment (optional): When needed, apply further alignment using preference data to improve helpfulness, safety, and stability.
Distillation reinforcement: Whether to run logits distillation depends on the availability of the teacher’s probabilities or logits. With a closed API, if logits are unavailable, fall back to output-based data distillation plus SFT. The teacher and student must use the same tokenizer and vocabulary. For large vocabularies, truncation or sparsification is needed. Suggested parameters:
- 50,000–200,000 distillation samples
- T between 2 and 6
- alpha between 0.3 and 0.8
- learning rate from 1e-5 to 5e-5
- 1–3 epochs, with early stopping based on the validation set
If the service terms prohibit using outputs to train other models, do not do so.
- Evaluation and iteration: Use a separate test set to evaluate accuracy, task success rate, P95 latency, throughput, memory usage, and cost per request. Use the results to close the loop of training, evaluation, and correction.
For deployment and metrics, record model versions, data versions, training parameters, and evaluation criteria. Track quality drift, latency, and cost changes through logs and monitoring. Engineering teams can decouple training, inference, storage, and monitoring. This article does not prescribe specific cloud products or providers.
License and Compliance Boundaries to Check Before Distillation
Can an organization be held liable if it self-hosts or distills someone else’s model? That mainly depends on whether the license and terms of service explicitly permit it and whether doing so violates applicable law. This article does not constitute legal advice. Refer to the original license terms or consult professional legal counsel for specifics.
Open source does not mean unconstrained. Different licenses impose different requirements for commercial use, derivative distillation, and redistribution.
| License Type | Commercial Use | Derivative Distillation | Redistribution | What to Check |
|---|---|---|---|---|
| Apache 2.0 | Generally permitted | Generally permitted | Generally permitted | Retain copyright notices and a copy of the license; document modifications |
| Llama Community License | May be permitted, subject to the terms | Depends on the acceptable use policy and additional restrictions | Depends on redistribution conditions | Acceptable use policy, naming requirements, attribution requirements, and scale restrictions |
| Custom community licenses | Varies widely | Varies widely | Varies widely | Review each clause to confirm whether distillation, commercial use, and redistribution are allowed |
When accessing closed models through an API, also read the terms of service. If the terms explicitly prohibit using outputs to train competing models or to scrape data, do not do so. Circumventing API restrictions or reverse engineering can not only violate the agreement, but also create legal risk.
Shift compliance work to the model selection stage:
- Prefer open-source models with clear licenses that explicitly allow further development and distillation.
- Be cautious when using closed APIs.
- Keep records of the sources and authorization of generated data.
- Remove and de-identify sensitive content, such as personal information and account credentials, before training data is ingested.
Common Distillation Failures and Troubleshooting
| Symptom | Possible Cause | Troubleshooting Action |
|---|---|---|
| Soft labels provide little benefit | Inappropriate temperature or low data quality | Adjust T; check data deduplication and noise |
| Excessive temperature hurts performance | Distribution is overly averaged | Compare T = 2, 4, and 6 on the validation set |
| Temperature is too low | Distribution is too peaked, weakening the value of soft labels | Raise T moderately and monitor validation loss |
| Student overfits to the teacher | Student is too strong or trained too much | Lower the learning rate, reduce epochs, increase the weight of hard labels |
| Black-box probabilities are unavailable | API does not return logprobs | Switch to output-based data distillation plus SFT |
| Teacher and student tokenizers differ | Different vocabularies or tokenization rules | Unify the tokenizer or adjust the distillation strategy |
Five-Point Engineering Checklist for Deploying Knowledge Distillation
- Build evaluation first, then distill: Define business metrics, test sets, and acceptance criteria up front, so you do not discover the wrong direction only after training.
- Prioritize data quality over quantity: High-quality, diverse instruction data raises the student’s performance ceiling more effectively than massive amounts of low-quality data.
- Keep the teacher–student capability gap moderate: When the gap is too large, the student struggles to fit the teacher. Introducing a mid-sized teacher for progressive distillation can help.
- Balance cost, accuracy, and latency: Clarify business priorities, then choose an appropriate student model size, quantization strategy, and inference configuration.
- Monitor and regression-test continuously: After each model iteration, watch for quality drift, and use logs and alerts to catch service degradation early.
Knowledge distillation is an important approach for building usable models under compute and cost constraints. Understanding its principles, mastering the engineering workflow, and respecting licensing and compliance boundaries are what allow organizations to turn large-model capabilities into product capabilities efficiently and responsibly.
