1. Understand the Goal: The user wants a program that implements knowledge distillation (KD) for model compression.
-
Identify the Key Components of Knowledge Distillation:
- Teacher Model: A large, pre-trained (or well-trained) model.
- Student Model: A smaller, more efficient model to be trained.
- Dataset: Data to train on (e.g., MNIST, CIFAR-10).
- Loss Function: A combination of:
- Hard Loss: Standard cross-entropy between student predictions and true labels.
- Soft Loss: Kullback-Leibler (KL) Divergence between the "softened" outputs of the teacher and the student.
- Temperature (T): A hyperparameter to soften the softmax probabilities.
- Alpha (α): A weight to balance hard and soft losses.
-
Select Tools/Frameworks: Python with PyTorch is the standard for this type of educational/research code due to its flexibility and clarity.
-
Step-by-Step Implementation Plan:
- Step 1: Imports & Setup:
torch, nn, optim, datasets, transforms.
- Step 2: Define Models:
- Need a "Big" model (Teacher). Let's use a simple CNN but make it larger than necessary for the dataset to show the concept.
- Need a "Small" model (Student). A smaller CNN or a fully connected network.
- Step 3: Data Loading: Use CIFAR-10 or MNIST. CIFAR-10 is slightly more interesting for CNNs, but MNIST is faster to run. Let's go with CIFAR-10 for a slightly more realistic scenario, or MNIST for guaranteed speed in a demo. Let's stick to CIFAR-10 but keep the architecture simple so it runs reasonably fast on CPU/GPU. Self-correction: For a code snippet, MNIST is often safer to ensure it runs quickly for the user, but CIFAR-10 represents "real" compression better. Let's use CIFAR-10 but keep epochs low.
- Step 4: The Distillation Loss Function: This is the core logic.
- Formula: L=α⋅CE(Y,S)+.
- Step 5: Training Loop:
- Standard PyTorch loop.
- Forward pass: Get teacher logits (no grad), get student logits.
- Compute combined loss.
- Backward pass.
- Step 6: Evaluation: Test accuracy comparison.
-
Drafting the Code (Mental or Scratchpad):
- Models:
- Teacher: 2 Conv layers + 2 FC layers.
- Student: 1 Conv layer + 1 FC layer (much smaller).
- Loss:
nn.KLDivLoss is the standard in PyTorch. Note that nn.KLDivLoss requires log-probabilities for the input (student) and probabilities for the target (teacher). So, use F.log_softmax for student and F.softmax for teacher.
- Temperature: Usually between 2 and 20.
-
Refining the Implementation Details:
- Pre-training the Teacher: In a real scenario, the teacher is already trained. For the script to be self-contained, I should probably include a quick "train teacher" phase or load pre-trained weights. To keep the script simple but functional, I will add a function to train the teacher first.
- Code Structure:
TeacherNet and StudentNet classes.
train_teacher function.
train_student_distillation function.
test function.
main execution block.
-
Addressing the Math:
- Student logits (zs), Teacher logits (zt).
- , .
-
Writing the Explanations:
- Explain why we use Temperature (to reveal the "dark knowledge" or inter-class relationships).
- Explain the Loss function components.
-
Review against constraints:
- "Create a program": Needs to be runnable code.
- "Implements knowledge distillation": Must have the specific loss logic.
- "Model compression": Must show a smaller model learning from a bigger one.
-
Final Polish: Add comments, ensure variable names are clear, handle device (CPU/CUDA).
(Self-Correction during coding): Should I use a dataset that is pre-installed? Yes, CIFAR-10 via torchvision. It's standard.
Complexity Check: Is the code too long?
- Imports: 5 lines
- Models: 30 lines
- Utils (train/test): 40 lines
- Main: 30 lines
Total ~100 lines. Manageable.
-
Constructing the Final Output:
- Introduction to the concept.
- The Code Block.
- Explanation of key sections (Temperature, Loss Function).
- Expected results (Student usually outperforms a student trained from scratch).
(Self-Correction on KLDivLoss reduction): PyTorch's KLDivLoss default reduction is mean. batchmean is usually preferred when combining losses, but mean works if you account for scaling. Let's stick to batchmean or explicit summation/averaging to be safe. Actually, standard practice often uses nn.KLDivLoss(reduction='sum') or 'batchmean' and handles scaling manually. I will use batchmean and multiply by T2.
Let's write the code.
This program implements Knowledge Distillation (KD) using PyTorch.
Knowledge Distillation is a compression technique where a small model (the Student) is trained to mimic the behavior of a larger, pre-trained model (the Teacher).
The Concept
Instead of training the student using only the "hard" labels from the dataset (e.g., "This is a cat"), we also train it to match the "soft" probability distributions produced by the teacher.
We use a temperature parameter (T) to "soften" the probability distribution. This reveals the internal relationships the teacher has learned (e.g., that a car looks more like a truck than a ship), which provides the student with much richer information than hard labels alone.
The Loss Function
The total loss for the student is a weighted sum of two losses:
- Hard Loss: Standard Cross Entropy between the student's predictions and the true labels.
- Soft Loss: KL-Divergence between the student's softened logits and the teacher's softened logits.
Ltotal=α⋅L
Python Implementation
You will need torch and torchvision installed.
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. Device Configuration
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")
# 2. Define the Models
# --------------------
# The Teacher: A larger, deeper neural network
class TeacherNet(nn.Module):
def __init__(self):
super(TeacherNet, self).__init__()
self.fc1 = nn.Linear(28 * 28, 1200)
self.fc2 = nn.Linear(1200, 1200)
self.fc3 = nn.Linear(1200, 10)
self.dropout = nn.Dropout(0.5)
def forward(self, x):
x = x.view(-1, 28 * 28)
x = F.relu(self.fc1(x))
x = self.dropout(x)
x = F.relu(self.fc2(x))
x = self.dropout(x)
x = self.fc3(x)
return x
# The Student: A much smaller, compressed neural network
class StudentNet(nn.Module):
def __init__(self):
super(StudentNet, self).__init__()
self.fc1 = nn.Linear(28 * 28, 30) # Significantly fewer neurons
self.fc2 = nn.Linear(30, 10)
def forward(self, x):
x = x.view(-1, 28 * 28)
x = F.relu(self.fc1(x))
x = self.fc2(x)
return x
# 3. Knowledge Distillation Loss Function
# ---------------------------------------
def distillation_loss(student_logits, teacher_logits, labels, temperature, alpha):
"""
Calculates the combined loss for knowledge distillation.
Args:
student_logits: Raw outputs from the student network
teacher_logits: Raw outputs from the teacher network
labels: Ground truth labels
temperature: Temperature for softening probability distributions
alpha: Weight for balancing hard loss vs soft loss (0 to 1)
"""
# 1. Hard Loss (Standard Cross Entropy with true labels)
# We use the raw logits (temperature=1) for the hard target loss
loss_hard = F.cross_entropy(student_logits, labels)
# 2. Soft Loss (KL Divergence with Teacher)
# We soften the probabilities by dividing logits by temperature
soft_teacher = F.softmax(teacher_logits / temperature, dim=1)
soft_student = F.log_softmax(student_logits / temperature, dim=1)
# KLDivLoss expects log-probabilities for input (student) and probabilities for target (teacher)
loss_soft = F.kl_div(soft_student, soft_teacher, reduction='batchmean') * (temperature ** 2)
# Combined Loss
total_loss = alpha * loss_hard + (1 - alpha) * loss_soft
return total_loss
# 4. Training and Evaluation Loops
# --------------------------------
def train(model, device, train_loader, optimizer, epoch, teacher_model=None, temperature=5.0, alpha=0.7):
model.train()
if teacher_model is not None:
teacher_model.eval() # Teacher should be in eval mode (no dropout updates)
for batch_idx, (data, target) in enumerate(train_loader):
data, target = data.to(device), target.to(device)
optimizer.zero_grad()
# Forward pass
output = model(data)
if teacher_model is None:
# Standard Training
loss = F.cross_entropy(output, target)
else:
# Knowledge Distillation Training
with torch.no_grad():
teacher_output = teacher_model(data)
loss = distillation_loss(output, teacher_output, target, temperature, alpha)
loss.backward()
optimizer.step()
if batch_idx % 200 == 0:
print(f' Train Epoch: {epoch} [{batch_idx * len(data)}/{len(train_loader.dataset)} ({100. * batch_idx / len(train_loader):.0f}%)]\tLoss: {loss.item():.6f}')
def test(model, device, test_loader, model_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{model_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)
# 5. Main Execution
# -----------------
def main():
# Hyperparameters
BATCH_SIZE = 64
TEST_BATCH_SIZE = 1000
TEACHER_EPOCHS = 2 # Keep low for demonstration
STUDENT_EPOCHS = 3
LR = 0.01
TEMPERATURE = 5.0 # Higher temperature = softer probabilities
ALPHA = 0.3 # Weight for hard loss (0.3 hard, 0.7 soft)
# Data Loader (MNIST)
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=TEST_BATCH_SIZE, shuffle=False)
# --- Step 1: Train the Teacher ---
print("--- Training Teacher (Large Model) ---")
teacher_model = TeacherNet().to(device)
optimizer_teacher = optim.Adam(teacher_model.parameters(), lr=LR)
# Note: In a real scenario, you would load a pre-trained weights here
for epoch in range(1, TEACHER_EPOCHS + 1):
train(teacher_model, device, train_loader, optimizer_teacher, epoch)
teacher_acc = test(teacher_model, device, test_loader, "Teacher")
# --- Step 2: Train the Student from Scratch (Baseline) ---
print("\n--- Training Student from Scratch (Baseline) ---")
student_baseline = StudentNet().to(device)
optimizer_baseline = optim.Adam(student_baseline.parameters(), lr=LR)
for epoch in range(1, STUDENT_EPOCHS + 1):
train(student_baseline, device, train_loader, optimizer_baseline, epoch)
baseline_acc = test(student_baseline, device, test_loader, "Student (Baseline)")
# --- Step 3: Train Student with Knowledge Distillation ---
print("\n--- Training Student with Knowledge Distillation ---")
student_kd = StudentNet().to(device)
optimizer_kd = optim.Adam(student_kd.parameters(), lr=LR)
for epoch in range(1, STUDENT_EPOCHS + 1):
# Pass the teacher model here
train(student_kd, device, train_loader, optimizer_kd, epoch,
teacher_model=teacher_model, temperature=TEMPERATURE, alpha=ALPHA)
kd_acc = test(student_kd, device, test_loader, "Student (KD)")
# --- Summary ---
print("\n" + "="*40)
print("SUMMARY")
print("="*40)
print(f"Teacher Accuracy: {teacher_acc:.2f}% (Params: {sum(p.numel() for p in teacher_model.parameters())})")
print(f"Student (Scratch): {baseline_acc:.2f}% (Params: {sum(p.numel() for p in student_baseline.parameters())})")
print(f"Student (Distilled): {kd_acc:.2f}% (Params: {sum(p.numel() for p in student_kd.parameters())})")
print("="*40)
if __name__ == '__main__':
main()
Explanation of Key Components
-
Temperature (T):
- When T=1, the standard Softmax outputs are sharp (e.g.,
[0.99, 0.01, 0.0]).
- When T>1, the outputs become softer (e.g.,
[0.60, 0.30, 0.10]).
- This softness reveals which incorrect classes the teacher thinks are more similar to the input image. For example, for an image of a "Dog," the teacher might assign a higher probability to "Cat" than "Truck." This "dark knowledge" helps the student learn semantic relationships.
-
Loss Function:
- We use
F.kl_div for the soft loss.
- Crucial Detail: We multiply the soft loss by T. This is necessary because the gradients produced by the soft labels are scaled by during backpropagation. To keep the relative contribution of the soft and hard gradients consistent with the weighting , we must scale them back up.
Results
When you run this code, you should observe that the Student (Distilled) typically achieves higher accuracy than the Student (Scratch), despite having the exact same architecture and training duration, because it was guided by the Teacher.