1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
| import torch import torch.nn as nn import torch.nn.functional as F import torchvision import torchvision.transforms as transforms from torch.utils.data import DataLoader
class TeacherCNN(nn.Module): def __init__(self): super(TeacherCNN, self).__init__() self.conv1 = nn.Conv2d(3, 16, kernel_size=3, padding=1) self.conv2 = nn.Conv2d(16, 32, kernel_size=3, padding=1) self.fc1 = nn.Linear(32 * 8 * 8, 10) self.relu = nn.ReLU() self.pool = nn.MaxPool2d(2, 2)
def forward(self, x): x = self.pool(self.relu(self.conv1(x))) x = self.pool(self.relu(self.conv2(x))) x = x.view(-1, 32 * 8 * 8) x = self.fc1(x) return x
class StudentCNN(nn.Module): def __init__(self): super(StudentCNN, self).__init__() self.conv1 = nn.Conv2d(3, 8, kernel_size=3, padding=1) self.conv2 = nn.Conv2d(8, 16, kernel_size=3, padding=1) self.fc1 = nn.Linear(16 * 8 * 8, 10) self.relu = nn.ReLU() self.pool = nn.MaxPool2d(2, 2)
def forward(self, x): x = self.pool(self.relu(self.conv1(x))) x = self.pool(self.relu(self.conv2(x))) x = x.view(-1, 16 * 8 * 8) x = self.fc1(x) return x
class DistillationLoss(nn.Module): def __init__(self, temperature=3.0): super(DistillationLoss, self).__init__() self.temperature = temperature
def forward(self, student_outputs, teacher_outputs, labels, alpha=0.5): soft_targets = F.softmax(teacher_outputs / self.temperature, dim=1) soft_prob = F.log_softmax(student_outputs / self.temperature, dim=1) soft_targets_loss = -torch.sum(soft_targets * soft_prob) * (self.temperature ** 2)
hard_loss = F.cross_entropy(student_outputs, labels)
loss = (alpha * soft_targets_loss) + ((1 - alpha) * hard_loss) return loss
def load_cifar10(batch_size=128): transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) ])
trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform) trainloader = DataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=2)
testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform) testloader = DataLoader(testset, batch_size=batch_size, shuffle=False, num_workers=2)
return trainloader, testloader
def evaluate_model(model, dataloader, device): model.eval() correct = 0 total = 0 with torch.no_grad(): for data, labels in dataloader: data, labels = data.to(device), labels.to(device) outputs = model(data) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item() return 100 * correct / total
def train_with_distillation(teacher_model, student_model, train_loader, test_loader, device, epochs=10, temperature=3.0, alpha=0.5): teacher_model.to(device) student_model.to(device)
teacher_model.eval() student_model.train()
optimizer = torch.optim.Adam(student_model.parameters()) distillation_criterion = DistillationLoss(temperature=temperature)
best_acc = 0.0
for epoch in range(epochs): running_loss = 0.0 for batch_idx, (data, target) in enumerate(train_loader): data, target = data.to(device), target.to(device)
optimizer.zero_grad()
with torch.no_grad(): teacher_output = teacher_model(data)
student_output = student_model(data)
loss = distillation_criterion(student_output, teacher_output, target, alpha=alpha)
loss.backward() optimizer.step()
running_loss += loss.item()
if batch_idx % 100 == 99: print(f'Epoch: {epoch + 1}, Batch: {batch_idx + 1}, ' f'Loss: {running_loss / 100:.4f}') running_loss = 0.0
student_acc = evaluate_model(student_model, test_loader, device) teacher_acc = evaluate_model(teacher_model, test_loader, device) print(f'\nEpoch {epoch + 1}:') print(f'Teacher Accuracy: {teacher_acc:.2f}%') print(f'Student Accuracy: {student_acc:.2f}%')
if student_acc > best_acc: best_acc = student_acc torch.save(student_model.state_dict(), 'best_student_model.pth')
return student_model
if __name__ == '__main__': device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
train_loader, test_loader = load_cifar10()
teacher_model = TeacherCNN() student_model = StudentCNN()
student_model = train_with_distillation( teacher_model=teacher_model, student_model=student_model, train_loader=train_loader, test_loader=test_loader, device=device, epochs=10, temperature=3.0, alpha=0.5 )
def count_parameters(model): return sum(p.numel() for p in model.parameters())
teacher_params = count_parameters(teacher_model) student_params = count_parameters(student_model)
print("\n模型大小比较:") print(f"教师模型参数数量: {teacher_params:,}") print(f"学生模型参数数量: {student_params:,}") print(f"压缩率: {(1 - student_params / teacher_params) * 100:.2f}% ")
|