RLHF:先从偏好学奖励,再用奖励改策略
Reinforcement learning from human feedback
跟踪三个回答的训练闭环,用精确KL最优解检查有限步策略梯度。
rlhf人选出了更好的回答,策略还需要一个学习信号
假设一个系统只能给出A、B、C三种回答。评审者可以在两个回答中选一个,却未必能给每个回答打出数值分。奖励模型把这些比较变成分数,策略再调整各回答出现的频率。这是两个不同的学习问题。即使分数遗漏了评审者在意的事,策略也可能很擅长把这个分数推高。
人类反馈强化学习(RLHF)用人类反馈指导强化学习。成对偏好学习是常见形式,不是唯一可能的定义。Christiano等人第2.2节在模拟控制与Atari中交替产生轨迹、收集人类比较、拟合奖励,使用的策略算法包括TRPO和A2C。Stiennon等人第3节把比较—奖励—策略流程用于摘要,从监督训练的语言模型出发,采用PPO。RLHF不总是PPO,也不是从一开始就专指聊天机器人训练。
本实验只有三个候选回答和人为构造的偏好频率。程序确实拟合奖励、训练策略,同时小到可以算出精确最优解。它没有人类受试实验、预训练语言模型或PPO实现。
把标签、奖励和策略分开
在序列环境中,一次比较可以针对整段轨迹。设观测为、动作为,一种简单的预测片段分数是:
这个不折扣的求和对应Christiano第2.2.3节的基础比较模型。片段长度、折扣或奖励归一化改变后,分数含义也会改变。语言生成则可以用一个标量模型,在提示的条件下给完整回答评分。
常见的比较假设是Bradley–Terry模型:A胜过B的概率取决于分数差,而非绝对分数。记:
对第个比较,令表示分配给第一个候选的目标概率。二元标签是特例,平局或汇总比较频率可以是软标签。平均负对数似然为:
负号不能漏:最小化这个损失才会奖励准确预测。程序用logaddexp避免溢出。本例只用基础逻辑模型,没有实现Christiano的完整集成、查询选择和随机回应混合配方;也不处理“无法比较”,不能擅自把无法判断当成平局。
接着冻结拟合好的奖励。对固定提示,设为个回答上的参考策略,为待学习策略。给定,常用的正则化目标是:
第二项惩罚。Stiennon第3.4节在序列层面使用参考概率惩罚;Rafailov等人第3—4节给出这个目标及闭式最优策略。KL会抑制不受限制的偏移,但不能保证行为准确或令人满意。奖励尺度变化,也会改变固定的实际约束强度。
为归一化约束引入拉格朗日乘子,对求导,得到加一个常数。归一化后:
程序对做softmax来计算。参考策略必须覆盖所有讨论中的回答。本例拒绝零参考概率:如果要求KL有限,就不能在参考支持集以外分配正概率。
我们没有用这个参照解替代训练,而是优化logit向量,令。定义,对完整有限期望求导:
求熵项导数时出现的额外常数,会因为softmax雅可比的求和为零而抵消。这是穷举后的精确策略梯度。语言模型通常无法枚举所有可能回答,采样式策略梯度处理的是另一种计算规模。
对任意候选分布,还能精确检查:
代入的表达式即可验证。这个恒等式同时检查目标与最优解,也能量出有限步训练的优化差距,不必假装程序已经收敛。
先训练奖励,再让策略对照精确解
以下完整程序需要Python与NumPy。比较顺序为(A,B)、(B,C)、(A,C),人为构造的目标是0.8, 0.8, 16/17,对应、与的奖励差。拟合后的中心化奖励约为。
"""Original three-response preference-to-policy loop; exact expectations, not PPO."""
import json
import numpy as np
def sigmoid(x):
x = np.asarray(x, dtype=float)
return np.exp(-np.logaddexp(0, -x))
def softmax(x):
x = np.asarray(x, dtype=float)
if x.ndim != 1 or not len(x) or not np.isfinite(x).all():
raise ValueError("Expected a nonempty finite vector")
e = np.exp(x - x.max())
return e / e.sum()
def preferences(scores, pairs):
return sigmoid(scores[pairs[:, 0]] - scores[pairs[:, 1]])
def pair_loss_grad(scores, pairs, targets):
scores = np.asarray(scores, dtype=float)
pairs = np.asarray(pairs, dtype=int)
targets = np.asarray(targets, dtype=float)
if (scores.ndim != 1 or pairs.ndim != 2 or pairs.shape[1] != 2
or len(pairs) == 0 or targets.shape != (len(pairs),)
or not np.isfinite(scores).all() or not np.isfinite(targets).all()
or np.any((targets < 0) | (targets > 1))
or pairs.min() < 0 or pairs.max() >= len(scores)):
raise ValueError("Invalid scores, pairs or soft labels")
delta = scores[pairs[:, 0]] - scores[pairs[:, 1]]
loss = np.mean(np.logaddexp(0, delta) - targets * delta)
residual = (sigmoid(delta) - targets) / len(pairs)
gradient = np.zeros_like(scores)
np.add.at(gradient, pairs[:, 0], residual)
np.add.at(gradient, pairs[:, 1], -residual)
return float(loss), gradient
def fit_scores(pairs, targets, size=3, steps=2000):
scores = np.zeros(size)
for _ in range(steps):
_, gradient = pair_loss_grad(scores, pairs, targets)
scores -= 0.5 * gradient
return scores
def policy_for_reward(reference, reward, beta):
reference = np.asarray(reference, dtype=float)
reward = np.asarray(reward, dtype=float)
if (reference.ndim != 1 or reference.shape != reward.shape
or not np.isfinite(reference).all() or not np.isfinite(reward).all()
or np.any(reference <= 0) or not np.isclose(reference.sum(), 1)
or not np.isfinite(beta) or beta <= 0):
raise ValueError("Positive normalized reference and beta are required")
return softmax(np.log(reference) + reward / beta)
PAIRS = np.array([[0, 1], [1, 2], [0, 2]])
def objective_grad(logits, reference, reward, beta):
# Validation and oracle share the same domain, not the optimizer.
policy_for_reward(reference, reward, beta)
p = softmax(logits)
logp = logits - np.logaddexp.reduce(logits)
advantage = reward - beta * (logp - np.log(reference))
value = p @ advantage
return float(value), p * (advantage - value)
def train_policy(reference, reward, beta, steps=3000):
logits = np.log(reference)
trace = []
for step in range(steps+1):
value, gradient = objective_grad(logits, reference, reward, beta)
if step % 300 == 0: trace.append([step, value])
if step < steps: logits += .3 * gradient
return softmax(logits), trace
def demo():
reference = np.array([.6, .3, .1])
# Authored fractional preference frequencies, not collected human labels.
targets = np.array([.8, .8, 16/17])
reward = fit_scores(PAIRS, targets)
results = []
for beta in [2., 1., .5]:
policy, trace = train_policy(reference, reward, beta)
oracle = policy_for_reward(reference, reward, beta)
results.append(dict(beta=beta, policy=policy.tolist(), oracle=oracle.tolist(),
max_error=float(np.max(abs(policy-oracle))),
expected_reward=float(policy@reward),
kl=float(policy@np.log(policy/reference)), trace=trace))
return dict(reference=reference.tolist(), targets=targets.tolist(),
learned_reward=reward.tolist(), results=results)
if __name__ == "__main__":
print(json.dumps(demo(), indent=2))
参考策略为(0.6, 0.3, 0.1),每个策略更新3,000步。时,精确答案为(96,12,1)/109,训练策略的最大概率误差约。时误差约。时仍约为:在当前logit参数化和步长下,第三个动作的微小概率收敛较慢。报告保留了这个残差。
对于个比较、个表格分数,奖励拟合每次全量更新需要工作量;策略更新需要工作量和内存。轨迹只每300步记录一次。这些成本描述有限教学模型,不代表Transformer训练或人类标注成本。
正确的优化器也可能认真优化一个错误分数
实验把两类误差分开:奖励学得不准确,以及没有把这个奖励优化到位。这里的合成概率特意来自假设中的逻辑模型,因此第一类问题格外容易。真实评审者可能意见不同,偏好可能依赖语境,新策略的输出也可能离开比较数据覆盖的范围。
奖励模型、策略和参考模型有不同职责,即使它们从同一个语言模型初始化也如此。监督微调提供示范,本身并不拟合比较偏好。采用PPO时,它是优化算法,不是人类价值的定义。留出比较集上的分数,与对生成回答的独立评测,回答的是不同问题。
三个回答的计算不能推出生产性能。评测真实流程时,应说明标注指南、数据划分、奖励校准、策略采样、参考模型与KL约定,以及新的评测流程。KL较小或奖励损失下降,都不足以单独证明目标达成。
分开检查三个阶段
- A胜过B的概率为0.8,基础模型对应多大的奖励差?
答案:赔率为,所以。这是模型中的尺度,不是人类幸福的计量单位。
- 每个奖励都加20,最优策略会变吗?
答案:不会。共同因子在归一化中抵消。目标值会增加20,但比较概率和最优策略不变。
- 对和奖励,求时的最优策略。
答案:未归一化权重为,总和2.725,得到。它可以独立检查梯度上升结果。
- 拟合奖励上升,新的人工评测却变差。梯度正确能排除这种情况吗?
答案:不能。梯度优化的是拟合分数与KL惩罚;奖励设定错误或分布偏移,都可能使分数改善偏离人类偏好。优化器正确,不等于奖励模型有效。
从轨迹反馈到语言偏好
Christiano第2.2节明确展示反馈闭环;Stiennon第3节展示语言生成场景;Rafailov第3—4节揭示正则目标,并引出另一种参数化。接着读奖励模型一篇,检查可识别性与代理失效,再读DPO的直接偏好优化。换一种算法,仍需要检查标签代表了谁的判断。
先判断,再看解释
最大化拟合奖励能保证人类认可吗?
学习目标
- 区分比较标签、学到的奖励与策略优化。
- 验证教学计算并说明它不能证明什么。
先修与延伸
查看知识关联图 →参考文献
- Deep Reinforcement Learning from Human Preferences — v1
Paul F. Christiano; Jan Leike; Tom B. Brown; Miljan Martic; Shane Legg; Dario Amodei · 2017 - Learning to summarize from human feedback — v1
Nisan Stiennon; Long Ouyang; Jeff Wu; Daniel M. Ziegler; Ryan Lowe; Chelsea Voss; Alec Radford; Dario Amodei; Paul F. Christiano · 2020 - Direct Preference Optimization: Your Language Model is Secretly a Reward Model — v2
Rafael Rafailov; Archit Sharma; Eric Mitchell; Stefano Ermon; Christopher D. Manning; Chelsea Finn · 2023
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(AI)
Codex · 2026-09-20 · Single AI author. Section2.2 through2.2.4 opening; PDF5 viewed: trajectory comparisons, soft labels, negative cross-entropy and actual recipe modifications. Sections3.1/3.4; PDF5/6 viewed. SFT/comparison/reward/PPO and KL penalty. Printed positive log-sigmoid loss sign is not copied as a minimization objective; see research note. Sections3/4, PDF3/4 viewed; gradient and procedure text read. BT, KL objective, partition cancellation and DPO; v2 dated2023-12-13. Seven paired equations and four explained exercises. Finite exact-expectation policy gradients, all-logit finite differences, KL gap identity and known optimum; beta0.5 finite-step residual retained. Synthetic labels, no PPO or human-feedback collection.
- 核全期望梯度、有限差分、KL差距恒等式与精确解;beta0.5残差保留,合成标签非PPO或真人试验。
- 每题四张计算SVG,10数值/几何与30响应式组合通过;实看10张最终图,完整页面验收另记。
核对的来源位置:
- Deep Reinforcement Learning from Human Preferences — v1 · Section2.2 through2.2.4 opening; PDF5 viewed: trajectory comparisons, soft labels, negative cross-entropy and actual recipe modifications.
- Learning to summarize from human feedback — v1 · Sections3.1/3.4; PDF5/6 viewed. SFT/comparison/reward/PPO and KL penalty. Printed positive log-sigmoid loss sign is not copied as a minimization objective; see research note.
- Direct Preference Optimization: Your Language Model is Secretly a Reward Model — v2 · Sections3/4, PDF3/4 viewed; gradient and procedure text read. BT, KL objective, partition cancellation and DPO; v2 dated2023-12-13.
相关主题