本篇解读DPOTrainer,这是TRL源码系列的最后一篇了,虽然还有好些trainer没有解读,例如:KTO, online DPO等,但都可以看作是PPO或者DPO的变种。最开始我以为本篇就一个DPO算法,但是后面发现自己太naive了,作者在源码里集成了太多的变种,想把所有变种都搞清楚但是时间不允许,因此变种部分仅做简要介绍。
1.DPO基础
(1)理论简介
DPO算法严格来说已经不是一种RL算法了,它可以直接根据preference data pair进行微调。但它确确实实又用到了RL的思想,它是利用Bradley-Terry模型和PPO目标函数推导出来的(推导过程见原论文附录Direct Preference Optimization:Your Language Model is Secretly a Reward Model),其中包含了隐式奖励函数。所以才会有论文的标题,说你的语言模型是一个隐藏的奖励模型。
由Bradley-Terry模型和PPO目标函数推导得到隐式奖励函数和DPO目标函数。
不得不说该算法十分精妙,从数学角度证明了,从奖励函数到最优策略的解析映射,省去了传统强化学习方法的复杂操作。
(2)数据输入
因为是直接从偏好数据进行学习,不同于PPO系列里的输入为prompt, DPO的输入与reward model类似,都是prompt+chosen response和prompt+rejected response。
(3)超参数介绍
https://github.com/huggingface/trl/blob/main/trl/trainer/dpo_config.py是DPOTrainer的超参数配置。
learning_rate: float = 1e-6
beta: float = 0.1
label_smoothing: float = 0.0
loss_type: Literal[
"sigmoid",
"hinge",
"ipo",
"exo_pair",
"nca_pair",
"robust",
"bco_pair",
"sppo_hard",
"aot",
"aot_pair",
"apo_zero",
"apo_down",
] = "sigmoid"
use_weighting: bool = False
label_pad_token_id: int = -100
padding_value: Optional[int] = None
truncation_mode: str = "keep_end"
max_length: Optional[int] = None
max_prompt_length: Optional[int] = None
max_target_length: Optional[int] = None # deprecated in favor of max_completion_length
max_completion_length: Optional[int] = None
is_encoder_decoder: Optional[bool] = None
disable_dropout: bool = True
generate_during_eval: bool = False
precompute_ref_log_probs: bool = False
dataset_num_proc: Optional[int] = None
model_init_kwargs: Optional[Dict[str, Any]] = None
ref_model_init_kwargs: Optional[Dict[str, Any]] = None
model_adapter_name: Optional[str] = None
ref_adapter_name: Optional[str] = None
reference_free: bool = False
force_use_ref_model: bool = False
f_divergence_type: FDivergenceType = FDivergenceType.REVERSE_KL
f_alpha_divergence_coef: float = 1.0
sync_ref_model: bool = False
ref_model_mixup_alpha: float = 0.9
ref_model_sync_steps: int = 64
rpo_alpha: Optional[float] = None
超参数实在太多了,我只解释比较难理解的,其他简单的可以直接看源码的说明:
beta: DPO 损失的温度,通常在 0.1 到 0.5 之间。它控制了我们对参考模型的关注程度,beta 越小,我们就越忽略参考模型(不理解的话,可以回到PPO目标函数公式看)。但因为loss_type有很多种,有的也背离了beta原来的意思;
label_smoothing: label的噪音比例,介于0.0-0.5之间;
loss_type: 不同损失函数的类型(后面会具体介绍),默认的是sigmoid;
use_weighting: 是否使用加权的DPO损失WPO;
label_pad_token_id: 用于pad label的token id, pad掉的token不计入损失,一般会把prompt的label pad掉;
precompute_ref_log_probs: 是否提前计算ref_log,如果提前计算可以在训练阶段减少GPU内存的使用
reference_free: 如果为TRUE,则忽略ref_model, ref_log的每一项默认均等分概率;
force_use_ref_model: 是否强制使用ref_model,当传递PEFT model的时候,可以替代单独的ref_model,如果强制使用则还是使用ref_model。
f_divergence_type: f散度类型,用于计算policy和reference模型输出的散度
f_alpha_divergence_coef: 当f_divergence_type是α散度时的α系数
sync_ref_model: TR-DPO的内容,DPOTrainer未使用
ref_model_mixup_alpha: TR-DPO的内容,DPOTrainer未使用
ref_model_sync_steps: TR-DPO的内容,DPOTrainer未使用
rpo_alpha: RPO的系数
2.DPO loss
(1)散度的计算
默认散度是KL散度 log(u),相当于代码里的chosen_logratios和rejected_logratios,注意u是不带log的policy/reference概率之比, 只有搞懂了这个,代码里α散度计算和JS散度计算的推导才能说得通。
如果reference_free为True,代表忽略reference model,ref_logratios是0,因为ref_chosen_logps 和 ref_rejected_logps是相同的等分概率,二者之差为0。
另外,根据DPO目标函数的计算公式可知道,logits = logratios - ref_logratios和logits = chosen_logratios - rejected_logratios是等价的。
# Get the log ratios for the chosen and rejected responses
chosen_logratios = chosen_logps.to(device) - (not self.reference_free) * ref_chosen_logps.to(device)
rejected_logratios = rejected_logps.to(device) - (not self.reference_free) * ref_rejected_logps.to(device)
if self.f_divergence_type == FDivergenceType.ALPHA_DIVERGENCE.value:
# The alpha-divergence formula: (1 - u^-alpha) / alpha
# The divergence difference between the chosen and rejected sample is:
# (1 - u[w]^-alpha) / alpha - (1 - u[l]^-alpha) / alpha
# = (u[l]^-alpha - u[w]^-alpha) / alpha
# where u[w] and u[l] are the policy/reference probability ratios
# for the chosen and rejected samples, respectively.
alpha_coef = FDivergenceConstants.ALPHA_DIVERGENCE_COEF_DEFAULT
if self.f_divergence_params and FDivergenceConstants.ALPHA_DIVERGENCE_COEF_KEY in self.f_divergence_params:
alpha_coef = float(self.f_divergence_params[FDivergenceConstants.ALPHA_DIVERGENCE_COEF_KEY])
logits = (cap_exp(rejected_logratios * -alpha_coef) - cap_exp(chosen_logratios * -alpha_coef)) / alpha_coef
else:
logratios = chosen_logps - rejected_logps
if self.reference_free:
ref_logratios = torch.tensor([0], dtype=logratios.dtype, device=logratios.device)
else:
ref_logratios = ref_chosen_logps - ref_rejected_logps
logratios = logratios.to(self.accelerator.device)
ref_logratios = ref_logratios.to(self.accelerator.device)
logits = logratios - ref_logratios
if self.f_divergence_type == FDivergenceType.JS_DIVERGENCE.value:
# The js-divergence formula: log(2 * u / (1 + u))
# The divergence difference between the chosen and rejected sample is:
# log(2 * u[w] / (1 + u[w])) - log(2 * u[l] / (1 + u[l]))
# = log(u[w]) - log(u[l]) - (log(1 + u[w]) - log(1 + u[l]))
# where u[w] and u[l] are the policy/reference probability ratios
# for the chosen and rejected samples, respectively.
logits -= F.softplus(chosen_logratios) - F.softplus(rejected_logratios)
(2)不同的loss
1)sigmoid
这是DPO的原始的损失函数logsigmoid, beta的作用在超参数里面已经说了,label_smoothing的作用主要是对label的不确定性进行一个trade-off,防止有脏标签。
其中ϵ是标签中噪声的比例(一般很小),就是代码里的label_smoothing
if self.loss_type == "sigmoid":
losses = (
-F.logsigmoid(self.beta * logits) * (1 - self.label_smoothing)
- F.logsigmoid(-self.beta * logits) * self.label_smoothing
)
2)robust
这是一个针对有噪声标签的专门损失函数 Robust DPO, 用于提升学习的鲁棒性。
Provably Robust DPO: Aligning Language Models with Noisy Feedback
elif self.loss_type == "robust":
losses = (
-F.logsigmoid(self.beta * logits) * (1 - self.label_smoothing)
+ F.logsigmoid(-self.beta * logits) * self.label_smoothing
) / (1 - 2 * self.label_smoothing)
3)exo_pair
EXO提出了一种高效精确优化的损失函数,旨在解决DPO收敛难的问题。
Towards Efficient Exact Optimization of Language Model Alignment
elif self.loss_type == "exo_pair":
# eqn (16) of the EXO paper: https://huggingface.co/papers/2402.00856
import math
if self.label_smoothing == 0:
self.label_smoothing = 1e-3
losses = (self.beta * logits).sigmoid() * (
F.logsigmoid(self.beta * logits) - math.log(1 - self.label_smoothing)
) + (-self.beta * logits).sigmoid() * (F.logsigmoid(-self.beta * logits) - math.log(self.label_smoothing))
后面的loss太多了,不作介绍了,感兴趣的自己去看论文吧
4)hinge
elif self.loss_type == "hinge":
losses = torch.relu(1 - self.beta * logits)
5) ipo
elif self.loss_type == "ipo":
# eqn (17) of the paper where beta is the regularization parameter for the IPO loss, denoted by tau in the paper.
losses = (logits - 1 / (2 * self.beta)) ** 2
6)bco_pair
elif self.loss_type == "bco_pair":
chosen_logratios = chosen_logps - ref_chosen_logps
rejected_logratios = rejected_logps - ref_rejected_logps
chosen_rewards = self.beta * chosen_logratios
rejected_rewards = self.beta * rejected_logratios
rewards = torch.cat((chosen_rewards, rejected_rewards), 0).mean().detach()
self.running.update(rewards)
delta = self.running.mean
losses = -F.logsigmoid((self.beta * chosen_logratios) - delta) - F.logsigmoid(
-(self.beta * rejected_logratios - delta)
)
7)sppo_hard
elif self.loss_type == "sppo_hard":
# In the paper (https://huggingface.co/papers/2405.00675), SPPO employs a soft probability approach,
# estimated using the PairRM score. The probability calculation is conducted outside of the trainer class.
# The version described here is the hard probability version, where P in Equation (4.7) of Algorithm 1 is
# set to 1 for the winner and 0 for the loser.
a = chosen_logps - ref_chosen_logps
b = rejected_logps - ref_rejected_logps
losses = (a - 0.5 / self.beta) ** 2 + (b + 0.5 / self.beta) ** 2
8)nca_pair
elif self.loss_type == "nca_pair":
chosen_rewards = (chosen_logps - ref_chosen_logps) * self.beta
rejected_rewards = (rejected_logps - ref_rejected_logps) * self.beta
losses = (
-F.logsigmoid(chosen_rewards)
- 0.5 * F.logsigmoid(-chosen_rewards)
- 0.5 * F.logsigmoid(-rejected_rewards)
)
9)aot_pair
elif self.loss_type == "aot_pair":
chosen_logratios = chosen_logps - ref_chosen_logps
rejected_logratios = rejected_logps - ref_rejected_logps
chosen_logratios_sorted, _ = torch.sort(chosen_logratios, dim=0)
rejected_logratios_sorted, _ = torch.sort(rejected_logratios, dim=0)
delta = chosen_logratios_sorted - rejected_logratios_sorted
losses = (
-F.logsigmoid(self.beta * delta) * (1 - self.label_smoothing)
- F.logsigmoid(-self.beta * delta) * self.label_smoothing
)
10)aot
elif self.loss_type == "aot":
logratios = chosen_logps - rejected_logps
ref_logratios = ref_chosen_logps - ref_rejected_logps
logratios_sorted, _ = torch.sort(logratios, dim=0)
ref_logratios_sorted, _ = torch.sort(ref_logratios, dim=0)
delta = logratios_sorted - ref_logratios_sorted
losses = (
-F.logsigmoid(self.beta * delta) * (1 - self.label_smoothing)
- F.logsigmoid(-self.beta * delta) * self.label_smoothing
)
11)apo_zero
elif self.loss_type == "apo_zero":
# Eqn (7) of the APO paper (https://huggingface.co/papers/2408.06266)
# Use this loss when you believe the chosen outputs are better than your model's default output
losses_chosen = 1 - F.sigmoid(self.beta * chosen_logratios) # Increase chosen likelihood
losses_rejected = F.sigmoid(self.beta * rejected_logratios) # Decrease rejected likelihood
losses = losses_chosen + losses_rejected
12)apo_down
elif self.loss_type == "apo_down":
# Eqn (8) of the APO paper (https://huggingface.co/papers/2408.06266)
# Use this loss when you believe the chosen outputs are worse than your model's default output.
# Decrease chosen likelihood and decrease rejected likelihood more
losses_chosen = F.sigmoid(self.beta * chosen_logratios)
losses_rejected = 1 - F.sigmoid(self.beta * (chosen_logratios - rejected_logratios))
losses = losses_chosen + losses_rejected
3.Loss的后处理
在函数get_batch_loss_metrics里面有几个可选的后续处理,根据配置相关,做个简要介绍。
(1)增加NLL loss——RPO
Iterative Reasoning Preference Optimization
if self.args.rpo_alpha is not None:
losses = losses + self.args.rpo_alpha * model_output["nll_loss"] # RPO loss from V3 of the paper
个人理解其中NLL loss相当于sft了chosen数据一次
if self.args.rpo_alpha is not None:
# Only use the chosen logits for the RPO loss
chosen_logits = logits[:num_examples]
chosen_labels = labels[:num_examples]
# Compute the log probabilities of the labels
output["nll_loss"] = F.cross_entropy(
torch.flatten(chosen_logits, end_dim=1), torch.flatten(chosen_labels, end_dim=1), ignore_index=0
)
(2)加权的DPO——WPO
WPO: Enhancing RLHF with Weighted Preference Optimization
if self.use_weighting:
losses = losses * model_output["policy_weights"]
其中权重公式计算如下:
if self.use_weighting:
with torch.no_grad():
# Eq (2) of the WPO paper: https://huggingface.co/papers/2406.11827
logprobs = F.log_softmax(logits, dim=-1)
weights_adjustment_factor = torch.logsumexp(2 * logprobs, dim=-1) # same as sum(probs**2) in log space
per_token_logps_adjusted = per_token_logps - weights_adjustment_factor
all_weights = (per_token_logps_adjusted * loss_mask).sum(-1) / loss_mask.sum(-1)
chosen_weights = all_weights[:num_examples]
rejected_weights = all_weights[num_examples:]
output["policy_weights"] = torch.clamp(torch.exp(chosen_weights + rejected_weights), max=1)
(3)添加辅助损失(Auxiliary Loss)
这是模型自带路由器辅助损失,跟RL无关,这里不作介绍。
if self.aux_loss_enabled:
losses = losses + self.aux_loss_coef * model_output["aux_loss"]