Knowledge Distillation
Knowledge Distillation
A technique that transfers the knowledge of a large model to a smaller one. Used for model compression.
Knowledge Distillation
A technique that transfers the knowledge of a large model to a smaller one. Used for model compression.
Knowledge Distillation is a model compression technique that transfers the knowledge of a large model (Teacher) to a small, efficient model (Student). By learning the Teacher model's output probability distribution (soft labels), the Student model receives richer information than it would by learning only the correct answers.
The concept of distillation was first proposed in the 2015 paper "Distilling the Knowledge in a Neural Network" by Geoffrey Hinton. It was followed by DistilBERT (2019), which compressed BERT to be 6 times smaller, and various attempts to make GPT lighter. In 2024-2025, DeepSeek-R1, Llama 3.2, Phi-4 and others drew attention as smaller models distilled from large models, and distillation has established itself as a key technology of the LLM era.
The core principle of distillation lies in "soft labels." For example, when classifying a cat image, the hard label is "cat=1, dog=0," but the Teacher's soft label is "cat=0.9, dog=0.08, tiger=0.02," which includes information about similarity between classes. The Temperature parameter softens the probability distribution so that this information is conveyed more effectively. Recently, techniques that distill even intermediate representations have advanced.
In practice, distillation is key to reducing model deployment costs. Distilling a 70B-parameter model into a 7B model can cut GPU costs by more than 90% while retaining 85-95% of the original performance. It is especially essential for reducing latency and cost in edge devices, mobile apps, and real-time services. As of 2025, most commercial LLM services also offer distilled models.
A basic knowledge distillation implementation using PyTorch:
# 지식 증류 (Knowledge Distillation) 기본 구현
import torch
import torch.nn as nn
import torch.nn.functional as F
class DistillationLoss(nn.Module):
"""
Knowledge Distillation Loss
- alpha: soft/hard loss 비율
- temperature: 확률 분포 smoothing
"""
def __init__(self, alpha=0.5, temperature=4.0):
super().__init__()
self.alpha = alpha
self.temperature = temperature
self.ce_loss = nn.CrossEntropyLoss()
self.kl_loss = nn.KLDivLoss(reduction='batchmean')
def forward(self, student_logits, teacher_logits, labels):
# Hard Loss: Student vs 실제 정답
hard_loss = self.ce_loss(student_logits, labels)
# Soft Loss: Student vs Teacher (temperature scaling)
T = self.temperature
soft_student = F.log_softmax(student_logits / T, dim=1)
soft_teacher = F.softmax(teacher_logits / T, dim=1)
soft_loss = self.kl_loss(soft_student, soft_teacher) * (T * T)
# 총 손실: alpha로 가중 평균
total_loss = self.alpha * soft_loss + (1 - self.alpha) * hard_loss
return total_loss
# 사용 예시
def train_with_distillation(student, teacher, dataloader, optimizer):
teacher.eval() # Teacher는 학습하지 않음
student.train()
criterion = DistillationLoss(alpha=0.7, temperature=4.0)
for inputs, labels in dataloader:
optimizer.zero_grad()
# Teacher 추론 (gradient 계산 안 함)
with torch.no_grad():
teacher_logits = teacher(inputs)
# Student 학습
student_logits = student(inputs)
loss = criterion(student_logits, teacher_logits, labels)
loss.backward()
optimizer.step()
print(f"Distillation 학습 완료!")
An example of LLM distillation using Hugging Face:
# Hugging Face 기반 LLM 증류 (DistilBERT 스타일)
from transformers import (
AutoModelForSequenceClassification,
AutoTokenizer,
Trainer,
TrainingArguments
)
from datasets import load_dataset
# Teacher: 대형 모델 (예: BERT-large)
teacher_name = "klue/roberta-large"
teacher = AutoModelForSequenceClassification.from_pretrained(
teacher_name, num_labels=2
)
# Student: 소형 모델 (예: DistilBERT)
student_name = "monologg/distilkobert"
student = AutoModelForSequenceClassification.from_pretrained(
student_name, num_labels=2
)
tokenizer = AutoTokenizer.from_pretrained(student_name)
# 커스텀 Trainer for Distillation
class DistillationTrainer(Trainer):
def __init__(self, teacher_model, alpha=0.5, temperature=4.0, **kwargs):
super().__init__(**kwargs)
self.teacher = teacher_model
self.teacher.eval()
self.alpha = alpha
self.temperature = temperature
def compute_loss(self, model, inputs, return_outputs=False):
labels = inputs.pop("labels")
# Student forward
student_outputs = model(**inputs)
student_logits = student_outputs.logits
# Teacher forward
with torch.no_grad():
teacher_outputs = self.teacher(**inputs)
teacher_logits = teacher_outputs.logits
# Distillation loss 계산
loss = distillation_loss(
student_logits, teacher_logits, labels,
self.alpha, self.temperature
)
return (loss, student_outputs) if return_outputs else loss
print("Student 모델 파라미터:", sum(p.numel() for p in student.parameters()))
print("Teacher 모델 파라미터:", sum(p.numel() for p in teacher.parameters()))
# 출력: Student가 Teacher 대비 약 40-60% 크기
Performance comparison of major distilled models (as of 2025):
| Model | Parameter | Size relative to original | Performance retention rate | Inference speed |
|---|---|---|---|---|
| BERT-base | 110M | 100% (original) | 100% | 1x |
| DistilBERT | 66M | 60% | 97% | 1.6x |
| Llama 3.1 70B | 70B | 100% (original) | 100% | 1x |
| Llama 3.2 8B (distilled) | 8B | 11% | ~90% | 8x+ |
| DeepSeek-R1-Distill-Qwen-7B | 7B | 1% (relative to 671B) | ~85% | 100x+ |
* Performance retention rate is based on the benchmark average; inference speed is a relative value on the same hardware.
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
If the Student is too small relative to the Teacher, it lacks the capacity to hold the knowledge. In general, 20-40% of the Teacher's size is appropriate, and reducing it to 10% or less causes performance to degrade sharply.
Leaving T=1 makes it similar to hard label training, which reduces the distillation effect. In most cases T=3~6 is optimal, and tuning is needed depending on the task.
Use Intermediate Layer Distillation together. Distilling hidden states as well, rather than only the final output, significantly improves performance. TinyBERT and MiniLM succeeded with this approach.