Knowledge Distillation
A technique for transferring the knowledge of a large model to a smaller model
A technique for transferring the knowledge of a large model to a smaller model
Knowledge Distillation is a model compression technique that transfers the knowledge of a large, complex Teacher model to a small, lightweight Student model. The key is to learn not the Teacher model's final prediction but the "soft target", that is, the entire probability distribution.
Proposed by Hinton in 2015, this technique has become a core technology for deployment on mobile and edge devices. When a GPT-4-class model cannot be deployed directly, the practical goal is to achieve similar performance with a small distilled model.
How it works: Temperature (T) is applied to the Teacher model's output to soften the probability distribution, and the Student learns this "dark knowledge." At T=1 it is the ordinary softmax, and the higher T is, the flatter the distribution becomes, conveying more information about relationships between classes.
In practice, Knowledge Distillation is used to compress BERT into DistilBERT (40% smaller, retaining 97% of performance) and to compress GPT into lightweight versions. The typical goal is to cut inference cost by more than 10x while keeping the performance loss under 5%.
import torch
import torch.nn as nn
import torch.nn.functional as F
class DistillationLoss(nn.Module):
"""Knowledge Distillation Loss 구현"""
def __init__(self, temperature=4.0, alpha=0.7):
super().__init__()
self.T = temperature
self.alpha = alpha # distillation loss 가중치
def forward(self, student_logits, teacher_logits, labels):
# 1. Hard Target Loss (실제 라벨과의 CE)
hard_loss = F.cross_entropy(student_logits, labels)
# 2. Soft Target Loss (Teacher 분포 학습)
soft_student = F.log_softmax(student_logits / self.T, dim=1)
soft_teacher = F.softmax(teacher_logits / self.T, dim=1)
soft_loss = F.kl_div(soft_student, soft_teacher, reduction='batchmean')
soft_loss = soft_loss * (self.T ** 2) # gradient 스케일 보정
# 3. 최종 Loss = alpha * soft + (1-alpha) * hard
return self.alpha * soft_loss + (1 - self.alpha) * hard_loss
# 사용 예시
teacher = BigModel().eval() # 고정
student = SmallModel()
criterion = DistillationLoss(temperature=4.0, alpha=0.7)
for images, labels in dataloader:
with torch.no_grad():
teacher_logits = teacher(images)
student_logits = student(images)
loss = criterion(student_logits, teacher_logits, labels)
loss.backward()
# Student만 1.2GB, Teacher 45GB -> 배포 시 Student만 사용
"Our GPT-4 API bill is 2 million KRW a month, but if we build a 7B model with Knowledge Distillation and deploy it on-premises, we can save 90%. Teacher-Student training will take 2 weeks, and we're targeting 92% of the original's performance."
"In the DistilBERT project, I set Temperature to 4.0 and alpha to 0.7 and compressed BERT-base by 40%. Soft targets also conveyed the relationships between classes, so F1 was 3% higher than with plain fine-tuning."
"Response-based distillation alone has its limits, so we're also matching intermediate-layer representations with feature-based distillation. If you add attention map alignment too, the Student learns the Teacher's reasoning patterns as well."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
When T is low, the probability distribution becomes sharp and dark knowledge isn't transferred. Experiment in the range T=3~6.
If you shrink it below 1/10 of the Teacher, it lacks the capacity to absorb the knowledge. 1/3 to 1/5 is the right range.
Always fix the Teacher in eval() mode and train only the Student. Tune the alpha value with validation in the range 0.5~0.9.