The user wants a program that implements knowledge distillation for model compression.
1. Understand the Goal:
Knowledge Distillation (KD) is a technique where a smaller "student" model learns to mimic a larger, pre-trained "teacher" model. The goal is to transfer the "dark knowledge" (the probability distribution over classes, not just the hard labels) from the teacher to the student.
2. Key Components Required:
- Teacher Model: A large, pre-trained model (e.g., a deep neural network).
- Student Model: A smaller, lightweight model.
- Loss Function: A combination of:
- Student Loss: Cross-entropy between student predictions and hard ground truth labels.
- Distillation Loss: Kullback-Leibler (KL) Divergence (or Cross-Entropy) between the "softened" student predictions and "softened" teacher predictions.
- Temperature (T): A hyperparameter used to soften the probability distributions (logits / T). High T produces a softer probability distribution.
- Alpha: A weight to balance the student loss and the distillation loss.
- Data: A dataset (e.g., MNIST or CIFAR-10 for demonstration).
- Framework: PyTorch is the most common and readable choice for this.
3. Structure of the Code:
- Imports: PyTorch, torchvision, etc.
- Model Definitions: Simple classes for Teacher (big) and Student (small). MLPs or simple CNNs are best for a standalone example.
- Distillation Loss Function: The core logic. Needs to handle softmax with temperature.
- Training Loop:
- Load data.
- Train the Teacher first (optional but good for demonstration, or load pre-trained). Self-correction: To keep the code runnable and self-contained, I should train the teacher briefly or just assume it's pre-trained. Training it briefly is safer to show the pipeline.
- Train the Student with KD.
- Evaluate both.
- Main execution block.
4. Drafting the KD Loss (The "Math" part):
- Logits zt (teacher), zs (student).
- Softmax with Temperature: pi=∑j.
- Loss: α⋅CE(y,ps)+(1−α.
5. Developing the Example Scenario:
- Dataset: MNIST is perfect. Small, fast to download, easy to visualize results.
- Teacher: A larger CNN (e.g., 2-3 conv layers).
- Student: A smaller CNN (e.g., 1-2 conv layers) or even a simple Linear network.
6. Refining the Code Steps:
- Step 1: Imports.
- Step 2: Model Classes.
TeacherNet, StudentNet.
- Step 3: Training Utils. Standard train/eval functions.
- Step 4: KD Loss Class/Function.
- Step 5: The Pipeline.
- Prepare data (MNIST).
- Initialize Teacher.
- Train Teacher (or load weights). Let's train it for a few epochs so the user sees the accuracy rise.
- Initialize Student.
- Train Student without KD (baseline).
- Train Student with KD (experiment).
- Compare sizes and accuracies.
7. Writing the Code (Mental Draft & Refinement):
- PyTorch specific details: Use
torch.nn.functional for softMax/log_softmax.
- Optimization: Adam or SGD. SGD is often standard for simple CNNs, Adam is faster.
- Code Clarity: Add comments explaining the temperature and the loss combination.
8. Addressing "Compression":
KD is knowledge transfer. The "compression" aspect comes from the fact that the Student has fewer parameters. I should explicitly calculate and print the parameter counts to demonstrate compression.
9. Final Polish:
- Add a
DistillationLoss class to make it modular.
- Ensure the code is copy-paste runnable (assuming PyTorch is installed).
- Add comments explaining why we do specific steps (like T2 scaling).
Self-Correction during drafting:
Should I use CIFAR-10 or ResNets?
Pros: More realistic.
Cons: Slower to train, requires downloading larger datasets, code gets longer.
Decision: Stick to MNIST with simple CNNs. It proves the concept effectively in seconds rather than minutes/hours. The logic applies identically to ResNet-50 distilling to MobileNet.
Structure of the Loss Function:
The Hinton et al. (2015) paper suggests using a weighted average of two objective functions.
- Cross Entropy with the hard labels (ground truth).
- Cross Entropy (KL Div) with the soft labels from the teacher.
The weighting usually puts less weight on the hard labels (e.g., 0.1) and more on the soft labels (0.9), or 50/50.
Temperature T controls the smoothness.
I will implement a custom loss class.
Let's write the actual code structure.
import torch
import torch.nn as nn
import torch.nn.functional as F
# ... imports ...
# 1. Define Models
class TeacherNet(nn.Module): ...
class StudentNet(nn.Module): ...
# 2. Define KD Loss
def distillation_loss(y, labels, teacher_scores, T, alpha):
# KD loss
# Hard label loss
# Return combined
# 3. Main loop
# Load data
# Train Teacher
# Train Student from scratch (optional, for comparison)
# Train Student with KD
# Compare
Specifics on the Loss implementation:
PyTorch's KLDivLoss takes (input, target). Input must be log-probs.
loss_kd = nn.KLDivLoss()(F.log_softmax(student_logits/T), F.softmax(teacher_logits/T)) * (T*T)
Note: The multiplication by T2 is important because the gradients scale by 1/T2 when softening, so we multiply back to maintain gradient magnitude.
10. Final Review of the Prompt:
"Create a program that implements knowledge distillation for model compression."
The output should be a complete, runnable Python script with explanations.
Let's generate the response based on this plan. I will use PyTorch as it is the standard research framework for this. I will include comments explaining the hyperparameters (T, α).
Plan:
- Introduction.
- Prerequisites.
- The Python Code (single file).
- Models.
- Loss Logic.
- Training Loop.
- Comparison.
- Explanation of the key parts (Temperature, Alpha).
Looks good. I will proceed.
Here is a complete, executable Python program using PyTorch to demonstrate Knowledge Distillation (KD).
The Concept
Knowledge Distillation compresses a large "Teacher" model into a smaller "Student" model. The student learns to mimic the logits (raw output scores) of the teacher, not just the hard labels (ground truth). This captures the "dark knowledge" (relationships between classes) contained in the teacher's probability distribution.
The Program
This script builds a deep Convolutional Neural Network (Teacher) and a lightweight one (Student). It trains the student using a combined loss of:
- Hard Target Loss: Standard Cross Entropy with ground truth labels.
- Soft Target Loss (KD Loss): Kullback-Leibler (KL) Divergence between the softened outputs of the Teacher and Student.
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
import time
# ---------------------------------------------------------
# 1. CONFIGURATION
# ---------------------------------------------------------
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
BATCH_SIZE = 64
EPOCHS = 3 # Keep low for demonstration
TEMPERATURE = 5.0 # Controls softness of probability distributions
ALPHA = 0.7 # Weight for KD Loss (0.7 means 70% KD, 30% Hard Labels)
LEARNING_RATE = 0.01
# ---------------------------------------------------------
# 2. MODEL DEFINITIONS
# ---------------------------------------------------------
class TeacherNet(nn.Module):
"""
A relatively large CNN for MNIST (approx 1.6M parameters).
It acts as the source of knowledge.
"""
def __init__(self):
super(TeacherNet, self).__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
self.dropout1 = nn.Dropout(0.25)
self.dropout2 = nn.Dropout(0.5)
self.fc1 = nn.Linear(9216, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = self.conv1(x)
x = F.relu(x)
x = self.conv2(x)
x = F.relu(x)
x = F.max_pool2d(x, 2)
x = self.dropout1(x)
x = torch.flatten(x, 1)
x = self.fc1(x)
x = F.relu(x)
x = self.dropout2(x)
logits = self.fc2(x)
return logits
class StudentNet(nn.Module):
"""
A very small CNN for MNIST (approx 18k parameters).
We want this to perform well by learning from the Teacher.
"""
def __init__(self):
super(StudentNet, self).__init__()
# Very simple architecture
self.conv1 = nn.Conv2d(1, 8, 3, 1) # Fewer filters
self.fc1 = nn.Linear(8 * 26 * 26, 10) # Direct mapping
def forward(self, x):
x = self.conv1(x)
x = F.relu(x)
x = torch.flatten(x, 1)
logits = self.fc1(x)
return logits
# ---------------------------------------------------------
# 3. KNOWLEDGE DISTILLATION LOGIC
# ---------------------------------------------------------
def distillation_loss(student_logits, teacher_logits, labels, temperature, alpha):
"""
Calculates the combined loss for Knowledge Distillation.
Formula: L_total = (1-alpha) * L_hard + alpha * L_soft
L_hard: CrossEntropy between student logits and true labels.
L_soft: KLDivergence between softened student and teacher logits.
"""
# 1. Soft Target Loss (KL Divergence)
# We soften the logits using Temperature. High T creates a softer probability
# distribution over classes, revealing which classes the teacher thinks are similar.
soft_targets = nn.functional.kl_div(
input=F.log_softmax(student_logits / temperature, dim=1),
target=F.softmax(teacher_logits / temperature, dim=1),
reduction="batchmean"
) * (temperature ** 2) # Scale the loss back up since gradients scale as 1/T^2
# 2. Hard Target Loss (Standard Cross Entropy)
hard_targets = nn.functional.cross_entropy(student_logits, labels)
loss = (1. - alpha) * hard_targets + alpha * soft_targets
return loss
# ---------------------------------------------------------
# 4. TRAINING & EVALUATION HELPERS
# ---------------------------------------------------------
def train_teacher(model, device, train_loader, optimizer, epoch):
model.train()
for batch_idx, (data, target) in enumerate(train_loader):
data, target = data.to(device), target.to(device)
optimizer.zero_grad()
output = model(data)
loss = F.cross_entropy(output, target)
loss.backward()
optimizer.step()
if batch_idx % 100 == 0:
print(f'Teacher Train Epoch: {epoch} [{batch_idx * len(data)}/{len(train_loader.dataset)}]\tLoss: {loss.item():.6f}')
def train_student_kd(student, teacher, device, train_loader, optimizer, epoch):
student.train()
teacher.eval() # Teacher is fixed, not training
for batch_idx, (data, target) in enumerate(train_loader):
data, target = data.to(device), target.to(device)
optimizer.zero_grad()
# Forward pass through both
student_logits = student(data)
with torch.no_grad(): # No gradients needed for teacher
teacher_logits = teacher(data)
loss = distillation_loss(student_logits, teacher_logits, target, TEMPERATURE, ALPHA)
loss.backward()
optimizer.step()
if batch_idx % 100 == 0:
print(f'Student (KD) Train Epoch: {epoch} [{batch_idx * len(data)}/{len(train_loader.dataset)}]\tLoss: {loss.item():.6f}')
def test(model, device, test_loader, name="Model"):
model.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for data, target in test_loader:
data, target = data.to(device), target.to(device)
output = model(data)
test_loss += F.cross_entropy(output, target, reduction='sum').item() # sum up batch loss
pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability
correct += pred.eq(target.view_as(pred)).sum().item()
test_loss /= len(test_loader.dataset)
print(f'\n{name} Test set: Average loss: {test_loss:.4f}, Accuracy: {correct}/{len(test_loader.dataset)} ({100. * correct / len(test_loader.dataset):.2f}%)\n')
return 100. * correct / len(test_loader.dataset)
def count_parameters(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
# ---------------------------------------------------------
# 5. MAIN EXECUTION PIPELINE
# ---------------------------------------------------------
def main():
# 1. Data Loading
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
dataset1 = datasets.MNIST('./data', train=True, download=True, transform=transform)
dataset2 = datasets.MNIST('./data', train=False, transform=transform)
train_loader = DataLoader(dataset1, batch_size=BATCH_SIZE, shuffle=True)
test_loader = DataLoader(dataset2, batch_size=BATCH_SIZE)
# 2. Initialize Models
teacher = TeacherNet().to(DEVICE)
student_kd = StudentNet().to(DEVICE)
# Create a copy of the student to train without KD for comparison
student_scratch = StudentNet().to(DEVICE)
print(f"Teacher Parameters: {count_parameters(teacher):,}")
print(f"Student Parameters: {count_parameters(student_kd):,}")
print("-" * 50)
# 3. Train Teacher
print("Training Teacher Model...")
optimizer_teacher = optim.Adam(teacher.parameters(), lr=LEARNING_RATE)
for epoch in range(1, EPOCHS + 1):
train_teacher(teacher, DEVICE, train_loader, optimizer_teacher, epoch)
test(teacher, DEVICE, test_loader, "Teacher")
# 4. Train Student with Knowledge Distillation
print("\nTraining Student with Knowledge Distillation...")
optimizer_student_kd = optim.Adam(student_kd.parameters(), lr=LEARNING_RATE)
for epoch in range(1, EPOCHS + 1):
train_student_kd(student_kd, teacher, DEVICE, train_loader, optimizer_student_kd, epoch)
test(student_kd, DEVICE, test_loader, "Student (KD)")
# 5. Train Student from scratch (Baseline)
print("\nTraining Student from scratch (Baseline)...")
optimizer_scratch = optim.Adam(student_scratch.parameters(), lr=LEARNING_RATE)
for epoch in range(1, EPOCHS + 1):
# Standard training loop without KD logic
student_scratch.train()
for batch_idx, (data, target) in enumerate(train_loader):
data, target = data.to(DEVICE), target.to(DEVICE)
optimizer_scratch.zero_grad()
output = student_scratch(data)
loss = F.cross_entropy(output, target)
loss.backward()
optimizer_scratch.step()
test(student_scratch, DEVICE, test_loader, "Student (Scratch)")
if __name__ == '__main__':
main()
How to Interpret the Results
When you run this script, observe the following:
- Parameter Count: The Teacher has significantly more parameters than the Student (roughly 100x more in this example).
- Accuracy:
- The Teacher will achieve the highest accuracy.
- The Student (KD) will usually significantly outperform the Student (Scratch).
- Compression vs. Performance: You will see that the Student (KD) achieves a "good enough" accuracy very close to the Teacher's, despite being a fraction of the size. The "Student (Scratch)" will likely struggle to converge or converge to a lower accuracy because it doesn't have the guidance of the soft labels.
Key Hyperparameters
TEMPERATURE (T):
T=1: Standard Softmax (Standard training).
T > 1: Produces a softer probability distribution. For example, if the teacher predicts a "7" with probability 0.99, and a "1" with 0.001, a high T smooths this out, telling the student "This looks slightly like a 1, but mostly a 7". This extra information helps the student generalize better.
ALPHA:
- Balances how much we trust the Teacher vs. the Ground Truth.
- Typically set between 0.5 and 0.9. A higher Alpha relies more on the Teacher's intuition.