在开源大模型微调实践中,损失函数的选择直接影响模型性能。最近在尝试微调Llama3-8B时,踩了不少坑。
问题背景:使用HuggingFace Transformers库微调,原始设置使用交叉熵损失(CrossEntropyLoss),但发现模型收敛缓慢且生成质量不佳。
踩坑记录:
- 默认损失函数问题:直接使用
torch.nn.CrossEntropyLoss()在多标签任务中表现差强人意 - 自定义损失函数尝试:尝试添加标签平滑(Label Smoothing)后效果提升明显
- 最终方案:结合Focal Loss和交叉熵的混合损失函数,收敛速度提升约40%
import torch
import torch.nn as nn
class MixedLoss(nn.Module):
def __init__(self, alpha=0.5, gamma=2.0, label_smoothing=0.1):
super().__init__()
self.alpha = alpha
self.gamma = gamma
self.label_smoothing = label_smoothing
def forward(self, logits, targets):
# 标签平滑交叉熵
ce_loss = nn.CrossEntropyLoss(label_smoothing=self.label_smoothing)
ce = ce_loss(logits, targets)
# Focal Loss
pt = torch.exp(-ce)
focal_loss = -self.alpha * (1-pt)**self.gamma * ce
return ce + focal_loss
复现步骤:
- 准备微调数据集
- 使用上述损失函数替换默认设置
- 调整学习率和批次大小
实测效果显著,推荐在开源模型微调中尝试此方案。

讨论