蒸馏知识点笔记

蒸馏(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()

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

相关推荐
mit6.82420 分钟前
[手机AI开发sdk] Aid_code IDE | PC浏览器同步访问
ide·人工智能·智能手机
deephub32 分钟前
FastMCP 入门:用 Python 快速搭建 MCP 服务器接入 LLM
服务器·人工智能·python·大语言模型·mcp
黑岚樱梦34 分钟前
代码随想录打卡day23:435.无重叠区间
算法
南宫乘风35 分钟前
基于 Flask + APScheduler + MySQL 的自动报表系统设计
python·mysql·flask
摇滚侠1 小时前
Spring Boot3零基础教程,Spring Boot 应用打包成 exe 可执行文件,笔记91 笔记92 笔记93
linux·spring boot·笔记
番石榴AI1 小时前
基于机器学习优化的主图选择方法(酒店,景点,餐厅等APP上的主图展示推荐)
图像处理·人工智能·python·机器学习
开开心心就好1 小时前
电子报纸离线保存:一键下载多报PDF工具
网络·笔记·macos·pdf·word·音视频·phpstorm
Kuo-Teng1 小时前
Leetcode438. 找到字符串中所有字母异位词
java·算法·leetcode
朝新_1 小时前
【SpringMVC】详解用户登录前后端交互流程:AJAX 异步通信与 Session 机制实战
前端·笔记·spring·ajax·交互·javaee
国产化创客1 小时前
基于AI大模型智能硬件--小智AI项目PC端部署测试
人工智能