大模型蒸馏技术全景:从 logits蒸馏到特征蒸馏

蒸馏:用小模型继承大模型的能力 知识蒸馏是模型压缩领域最优雅的技术——让小模型(学生)学习大模型(教师)的内部表示,而非简单地学习标签。一个好的蒸馏方案可以让7B模型逼近70B模型的效果。 Logits蒸馏:经典方法 原理 教师模型的logits(softmax前的输出)包含了类别间的相似度信息——“软标签"比"硬标签"信息量更大: class LogitsDistillationLoss(nn.Module): def __init__(self, temperature=2.0, alpha=0.5): self.temperature = temperature self.alpha = alpha # 蒸馏loss与CE loss的权重比 def forward(self, student_logits, teacher_logits, labels): # 蒸馏损失:KL散度 soft_teacher = F.log_softmax( teacher_logits / self.temperature, dim=-1 ) soft_student = F.log_softmax( student_logits / self.temperature, dim=-1 ) distill_loss = F.kl_div( soft_student, soft_teacher.exp(), reduction="batchmean" ) * (self.temperature ** 2) # 标准交叉熵损失 ce_loss = F.cross_entropy(student_logits, labels) return self.alpha * distill_loss + (1 - self.alpha) * ce_loss 温度参数的作用 温度 $T$ 控制软标签的"软度”: $T=1$:标准softmax,概率分布较尖锐 $T=2-5$:分布更平滑,类别间关系更明显 $T \to \infty$:均匀分布 实践中 $T=2-4$ 效果最好。温度的平方项补偿了梯度缩放——高温softmax的梯度会被 $1/T^2$ 缩小。 在线蒸馏vs离线蒸馏 离线蒸馏:先训练好教师模型,再蒸馏学生模型。简单稳定但教师的错误会被继承。 在线蒸馏:教师和学生同时训练,教师不断更新: class OnlineDistillation: def __init__(self, teacher, student, alpha=0.5): self.teacher = teacher self.student = student self.alpha = alpha def train_step(self, batch): # 教师前向(不更新梯度) with torch.no_grad(): teacher_logits = self.teacher(batch) # 学生前向 student_logits = self.student(batch) # 蒸馏损失 distill_loss = self._distill_loss(student_logits, teacher_logits) ce_loss = F.cross_entropy(student_logits, batch["labels"]) loss = self.alpha * distill_loss + (1 - self.alpha) * ce_loss loss.backward() 特征蒸馏:学习中间表示 原理 Logits蒸馏只利用了最终输出,特征蒸馏还利用了中间层的表示: ...

2026-07-16 · 3 min · 481 words · 硅基 AGI 探索者
鲁ICP备2026018361号