Knowledge Distillation for Large Language Models: Principles, Practice, and Compliance Boundaries
Knowledge distillation transfers the capabilities of a large teacher model to a smaller, cheaper student model, reducing inference latency and deployment cost while preserving task performance. This article explains the three goals of distillation (compression, task improvement, data augmentation), the role of soft labels and the temperature parameter, a PyTorch implementation of the combined distillation loss, three mainstream distillation routes, key engineering practices, and the licensing and compliance boundaries every team should review before starting a distillation project.
1. What Knowledge Distillation Solves
Knowledge Distillation (KD) transfers the knowledge of a capable teacher model to a smaller or cheaper-to-train student model. Its value lies in preserving as much task performance as possible when inference latency, GPU memory, and deployment costs are constrained.
In the LLM context, distillation typically serves three goals:
- Compressing model size to reduce inference cost and per-request latency;
- Improving small and mid-sized models on specific tasks such as code generation, structured information extraction, and customer service Q&A;
- Generating training samples with the teacher model to expand data scale when labeled data is scarce.
Understanding these goals helps you choose a distillation route. For pure compression, focus on student architecture and quantization strategy; for task improvement, focus on data construction and the evaluation framework.
2. Soft Labels and the Temperature Parameter
Traditional supervised learning uses hard labels (one-hot encoding), which only tell the model which token is correct. The teacher’s output distribution contains far more information: the relative probabilities of other candidate tokens reflect semantic similarity and reasoning tendencies. This information is collectively called soft labels.
To smooth the soft-label distribution, a temperature parameter T is introduced into the softmax:
q_i = exp(z_i / T) / Σ_j exp(z_j / T)
where z_i is the logit of the i-th token. A larger T produces a smoother distribution and makes low-probability candidates more informative. In practice, T is usually set between 1 and 4, combined with a weighted hard-label loss. T and the learning rate should be tuned together — poor settings for either destabilize training.
3. Implementing the Distillation Loss
The example below shows a common combined loss in PyTorch. Since language model logits are typically 3D tensors (batch, sequence length, vocab size), they are flattened to 2D first.
import torchimport torch.nn.functional as Fdef distillation_loss(student_logits, teacher_logits, labels,T=2.0, alpha=0.5):# Flatten to (samples, vocab_size); each position is one classification samplevocab_size = student_logits.size(-1)student_logits = student_logits.reshape(-1, vocab_size)teacher_logits = teacher_logits.reshape(-1, vocab_size)labels = labels.reshape(-1)# Soft-label loss: match the teacher distribution; multiply by T^2 to# counteract gradient scaling introduced by temperaturesoft_loss = F.kl_div(F.log_softmax(student_logits / T, dim=-1),F.softmax(teacher_logits.detach() / T, dim=-1),reduction="batchmean",) * (T * T)# Hard-label loss: retain supervision from ground-truth labelshard_loss = F.cross_entropy(student_logits, labels)return alpha * soft_loss + (1 - alpha) * hard_loss
Three implementation notes. First, the teacher only performs forward passes — run it under torch.no_grad() or use detach() to block gradients. Second, kl_div requires log-probabilities as input and probabilities as the target; do not reverse the order. Third, alpha controls the weighting between soft and hard labels; search it on a validation set, with 0.5 as a common starting point.
4. Three Common Distillation Routes
Depending on the type of signal available, distillation falls into three main routes.
1. Output distribution (logit-based)
The student directly fits the teacher’s token probability distribution, as in the loss above. This carries the most information but requires access to the teacher’s full output probabilities. It suits scenarios where you own the teacher model or have full authorization to use it.
2. Intermediate representations (feature-based)
The student’s hidden-layer representations are aligned with the teacher’s corresponding layers. Since dimensions usually differ, projection layers are needed for mapping. This transfers deeper structural information but is complex to implement, costly to train, and requires careful selection of alignment layers.
3. Generated content (sequence-level or data distillation)
The teacher generates complete responses for a set of inputs, and the student is fine-tuned on these texts. This has the lowest barrier to entry and is the most widely used. The trade-off is that only final text is retained — probability distribution information is lost, and the student’s ceiling is generally lower than with the first two routes.
Comparison of the three routes:
| Route | Required Signal | Information Richness | Implementation Cost | Typical Scenario |
|---|---|---|---|---|
| Output distribution | Full probability distribution | High | Medium | Compressing in-house models |
| Intermediate representations | Hidden-layer activations | Very high | High | Structural transfer research |
| Generated content | Final text | Medium | Low | Task data augmentation |
5. Engineering Best Practices
Prioritize data quality. Training samples should be deduplicated, filtered for low-quality content, and stripped of harmful or sensitive samples. Teacher-generated data also carries the teacher’s own errors, so sample reviews are necessary. The sample distribution should closely match real production requests, or the student’s online performance will degrade noticeably.
Keep the teacher-student capability gap reasonable. The teacher must be clearly stronger than the student for distillation to yield gains. If the gap is too large, the student may fail to learn the teacher’s complex reasoning patterns and instead produce unstable output quality.
Monitor the training process. Beyond loss curves, regularly evaluate the student on a validation set. If training loss keeps falling while validation metrics stall or regress, the student is overfitting the teacher’s biases — reduce the learning rate or increase data diversity.
Evaluate at the task level. Perplexity only reflects language modeling ability, not business outcomes. Evaluation should include task benchmarks, format-following rates, factual accuracy, safety checks, and manual spot checks.
Deployment still requires optimization. A distilled model typically still needs quantization, batching/scheduling tuning, and KV cache optimization to meet production throughput and latency requirements. These steps are independent of distillation itself and should be validated separately.
6. Licensing and Compliance Boundaries
Distillation involves intellectual property and terms of service — the risk point engineering teams most easily overlook. Calling a third-party model service and using its outputs to train your own model may violate the service agreement’s data-use clauses. This risk does not disappear regardless of how the technique is implemented.
Service providers commonly deploy protective measures such as rate limiting, anomaly detection on query patterns, output watermarking, and access controls. These mechanisms directly affect the feasibility of large-scale data generation. For callers, the following should be completed at project kickoff:
- Confirm whether the terms of service allow outputs to be used for model training, and keep versioned records of the relevant clauses;
- Prefer your own data, openly licensed datasets, or data you are authorized to generate samples from;
- Maintain a data provenance ledger recording the source, license scope, and processing of each training data batch;
- Integrate compliance review into the model release process rather than treating it as an afterthought.
7. Launch Checklist
Before starting a distillation project, confirm each item:
- Define whether the goal is compression, task improvement, or data augmentation, and choose the route accordingly;
- Verify usage rights and data terms for the teacher model;
- Complete deduplication, filtering, and sample review of training data;
- Set search ranges for temperature, loss weights, and learning rate, and record results on a validation set;
- Evaluate the student with both task-level benchmarks and manual spot checks;
- Complete quantization and inference performance testing before deployment, with a rollback plan in place.
