蒸馏知识点笔记

蒸馏(Distillation)

模型蒸馏是一种通过将大模型(教师模型)的知识传递给小模型(学生模型)来优化小模型性能的方法。蒸馏通常包括以下几种形式:

1. 软标签蒸馏(Soft Label Distillation)

通过教师模型的软标签(soft labels)来训练学生模型,使学生模型学习教师模型的输出分布。

python 复制代码
import torch
import torch.nn as nn

# 定义教师模型和学生模型
teacher_model = ...
student_model = ...

# 定义损失函数
criterion = nn.KLDivLoss(reduction='batchmean')

# 教师模型生成软标签
teacher_model.eval()
with torch.no_grad():
    teacher_outputs = teacher_model(inputs)
soft_labels = torch.softmax(teacher_outputs / temperature, dim=1)

# 学生模型预测
student_outputs = student_model(inputs)
loss = criterion(torch.log_softmax(student_outputs / temperature, dim=1), soft_labels)

# 反向传播和优化
loss.backward()
optimizer.step()

2. 特征蒸馏(Feature Distillation)

通过让学生模型学习教师模型中间层的特征表示来优化学生模型性能。

python 复制代码
class FeatureExtractor(nn.Module):
    def __init__(self, model):
        super(FeatureExtractor, self).__init__()
        self.features = nn.Sequential(*list(model.children())[:-1])
    
    def forward(self, x):
        return self.features(x)

teacher_feature_extractor = FeatureExtractor(teacher_model)
student_feature_extractor = FeatureExtractor(student_model)

# 获取特征表示
teacher_features = teacher_feature_extractor(inputs)
student_features = student_feature_extractor(inputs)

# 定义特征蒸馏损失
feature_distillation_loss = nn.MSELoss()(student_features, teacher_features)

# 反向传播和优化
feature_distillation_loss.backward()
optimizer.step()

3. 组合蒸馏(Combined Distillation)

结合软标签蒸馏和特征蒸馏,利用教师模型的输出分布和特征表示来训练学生模型。

python 复制代码
# 定义损失函数
criterion = nn.KLDivLoss(reduction='batchmean')
mse_loss = nn.MSELoss()

# 教师模型生成软标签
teacher_model.eval()
with torch.no_grad():
    teacher_outputs = teacher_model(inputs)
soft_labels = torch.softmax(teacher_outputs / temperature, dim=1)

# 学生模型预测
student_outputs = student_model(inputs)
soft_label_loss = criterion(torch.log_softmax(student_outputs / temperature, dim=1), soft_labels)

# 获取特征表示
teacher_features = teacher_feature_extractor(inputs)
student_features = student_feature_extractor(inputs)
feature_loss = mse_loss(student_features, teacher_features)

# 组合损失
total_loss = soft_label_loss + alpha * feature_loss

# 反向传播和优化
total_loss.backward()
optimizer.step()

通过上述蒸馏技术,可以有效地优化模型结构,减少计算开销,并在保持模型性能的前提下,提高模型的推理速度和部署效率。

相关推荐
机器之心1 分钟前
近80年后,埃尔德什经典「拉姆齐数下界」,被三位中国学者首次指数级改进
人工智能·openai
机器之心5 分钟前
Nvidia都在点赞的LoopWM世界模型,竟然来自一家中国初创FaceMind?
人工智能·openai
美团技术团队1 小时前
LongCat 开源 VitaBench 2.0:长期动态智能体基准新标杆
人工智能·算法
moMo1 小时前
从“你好”到 1024 维坐标:大模型怎么识字
人工智能
ShallWeL1 小时前
【机器学习】(2)—— 线性回归:损失函数
人工智能·机器学习
美团技术团队2 小时前
ICML 2026 | 美团技术团队学术论文精选
人工智能
moMo2 小时前
你的每一次对话,都是第一次
人工智能
不加辣椒2 小时前
第13章 检索增强提示工程
人工智能
小爷毛毛_卓寿杰2 小时前
我把 397B 的「Agentic 大脑」塞进了 Xinference,一键部署 Nex-N2
人工智能·架构·github
smallYoung2 小时前
Vibe Coding 笔记-中
人工智能