蒸馏知识点笔记

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

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

相关推荐
weixin_422456445 分钟前
第N7周:调用Gensim库训练Word2Vec模型
人工智能·机器学习·word2vec
不太可爱的叶某人1 小时前
【学习笔记】MySQL技术内幕InnoDB存储引擎——第5章 索引与算法
笔记·学习·mysql
FreakStudio2 小时前
一文速通 Python 并行计算:13 Python 异步编程-基本概念与事件循环和回调机制
python·pycharm·协程·多进程·并行计算·异步编程
归去_来兮2 小时前
深度学习模型在C++平台的部署
c++·深度学习·模型部署
HuggingFace3 小时前
Hugging Face 开源机器人 Reachy Mini 开启预定
人工智能
豌豆花下猫3 小时前
让 Python 代码飙升330倍:从入门到精通的四种性能优化实践
后端·python·ai
夏末蝉未鸣014 小时前
python transformers库笔记(BertForTokenClassification类)
python·自然语言处理·transformer
企企通采购云平台4 小时前
「天元宠物」×企企通,加速数智化升级,“链”接萌宠消费新蓝海
大数据·人工智能·宠物
超级小忍4 小时前
Spring AI ETL Pipeline使用指南
人工智能·spring
YuTaoShao4 小时前
【LeetCode 热题 100】141. 环形链表——快慢指针
java·算法·leetcode·链表