蒸馏知识点笔记

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

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

相关推荐
Zhao-Jichao7 分钟前
AI Prompting for Everyone 课程笔记 - P20 实验与期末项目 Lab and Final Project
前端·人工智能·笔记
敢敢のwings14 分钟前
TACDYN-WAM 深度解读:机器人如何预测接触变化,并据此生成动作
人工智能·机器学习·机器人
沉默王二17 分钟前
阿里版Codex,再次惊艳到我了。
人工智能·openai·agent
正在走向自律19 分钟前
【1/5】人工智能训练师 一级/高级技师 考证学习方向:从“可评审的交付”到“可定义的标准与可传承的体系”
人工智能·人工智能训练师·一级/特级·ai技术负责人·数据体系负责人·行业解决方案架构·技术评审与标准制定
时文鲜读23 分钟前
算力基建提速,数据中心安全建设与工业可靠性如何同步升级?
大数据·人工智能·安全
坐吃山猪25 分钟前
果蝇AI07-Mac部署踩坑
人工智能·深度学习·机器学习·果蝇ai
挖掘狂人25 分钟前
AI PC 分水岭:2026 过半 PC 搭载本地 AI,端云协同才是核心
人工智能·程序员·ai编程
一去不复返的通信er30 分钟前
排序 + 双指针:力扣15三数之和
算法·leetcode
吴名氏.36 分钟前
Java转AI Agent教程(第九周)错误矩阵
java·人工智能·矩阵·ai agent
用户03321266636738 分钟前
使用 Python 在 Excel 文档中添加水印
python·excel