def token_credit(p1, p2, r):
"""For two-digit responses y = 10 a1 + a2: pi(y | x), the response
weight r - V(x) and the token advantages A(s_1, a1), A(s_2, a2)."""
a1, a2 = np.divmod(np.arange(100), 10)
prob = p1[a1] * p2[a2]
V_x, V_xa = prob @ r, r.reshape(10, 10) @ p2 # V(x), V(x, a1)
return prob, r - V_x, V_xa[a1] - V_x, r - V_xa[a1]15.8 面向序列生成的强化学习
本书此前介绍的每个语言模型都是通过模仿文本训练的,这本质上是对语料作者的行为克隆(14.5 节)。而如今人们使用的模型还会接受进一步训练,所依赖的信号并不存在于任何静态语料中:验证器判定解答的最终答案是否正确,或者评审者指出两个回答中哪一个更好。得分只在模型自己写完整个回答后给出一次,没有任何可供照抄的目标词元。14.7 节 与 14.8 节 已在四个算术提示和验证器上训练过此类策略。
这一思想早于现代大语言模型。Christiano 等 (2017年) 从人类偏好比较中拟合奖励并用策略梯度优化;Ouyang 等 (2022年) 将其应用于大语言模型,并加入防止偏离监督模型的惩罚;Shao 等 (2024年) 用一组采样替代价值网络,而 DeepSeek-AI (2025年) 则用确定性验证器取代了学习奖励模型。
当每个回答只拿到一个标量奖励时,逐词元视角还能增添什么?15.3 节 的惩罚又能在多大程度上拉住已经发现漏洞的策略?本节通过回答这两个问题,用 14.8 节 的组权重、15.2 节 的概率比与裁剪以及该 KL 惩罚,完整拼装出后训练更新规则。
15.8.1 将回答视作一条轨迹
15.8.1.1 同一个梯度,两种视角
针对提示 \(x\) 的回答 \(y = (a_1, \ldots, a_T)\) 是一条以词元为动作的轨迹(表 15.8.1)。第 \(t\) 个词元之前的状态是前缀 \(s_t = (x, a_1, \ldots, a_{t-1})\),拼接 \(a_t\) 以概率 1 转移到 \(s_{t+1}\),因此整条回答的概率等于各词元概率之积 \(\pi_\theta(y \mid x) = \prod_t \pi_\theta(a_t \mid s_t)\),且
\[\nabla_\theta \log \pi_\theta(y \mid x) = \sum_{t=1}^{T} \nabla_\theta \log \pi_\theta(a_t \mid s_t). \tag{15.8.1}\]
| 语言建模 | 强化学习 |
|---|---|
| 提示 \(x \sim \mu_0\) | 初始状态 \(s_1\) |
| 词元 \(a_t\) | 动作 \(a_t\) |
| 前缀 \((x, a_1, \ldots, a_{t-1})\) | 状态 \(s_t\) |
| 完整回答 \(y = (a_1, \ldots, a_T)\) | 轨迹 \(\tau\) |
| 以 EOS 结尾的前缀 \((x, y)\) | 终止状态 |
| 下一词元分布 | 策略 \(\pi_\theta(a_t \mid s_t)\) |
| 验证器或奖励模型得分 \(r(x, y)\) | 终止奖励 |
式 15.8.1 的左端把整个回答看作单个动作,右端则看作 \(T\) 个词元动作。由于末尾只有一个奖励 \(r(x, y)\) 且无折扣,每个词元的未来回报都是 \(r(x, y)\),因此对任意仅依赖提示的基线 \(b(x)\),两种视角都用同一个回答权重 \(r(x, y) - b(x)\) 去乘每个词元的计分。
15.8.1.2 回答内部的信用分配
回答权重虽然无偏,却把所有词元一视同仁——哪怕错误答案中也有写对的词元。设提示 3*4 由十位数字 \(a_1\) 和个位数字 \(a_2\) 回答,两者均在 \(0, \ldots, 9\) 上均匀分布。只有 12 正确,因此 \(V(x) = 1/100\),\(V(x, 1) = 1/10\),对其余所有十位数字 \(V(x, a_1) = 0\)。回答 13 得分为 \(0\),在两个词元上都获得权重 \(r - V(x) = -0.01\),连带把正确的十位数字也往下压。而 14.8 节 的词元优势改为以前缀为条件:十位数字获得 \(A(s_1, a_1) = V(x, a_1) - V(x) = +0.09\),个位数字获得 \(A(s_2, a_2) = r - V(x, a_1) = -0.1\)。函数 token_credit 为全部一百个回答 \(y = 10 a_1 + a_2\) 计算 \(\pi(y \mid x)\)、回答权重以及两个词元优势:
def token_credit(p1, p2, r):
"""For two-digit responses y = 10 a1 + a2: pi(y | x), the response
weight r - V(x) and the token advantages A(s_1, a1), A(s_2, a2)."""
a1, a2 = np.divmod(np.arange(100), 10)
prob = p1[a1] * p2[a2]
V_x, V_xa = prob @ r, r.reshape(10, 10) @ p2 # V(x), V(x, a1)
return prob, r - V_x, V_xa[a1] - V_x, r - V_xa[a1]我们打印三个回答的三种权重,验证回答权重与十位词元优势对十位数字(计分为 \(\mathbf{e}_{a_1} - \mathbf{p}_1\))给出相同的期望梯度,并比较这些零均值权重的方差:
y = np.arange(100) # the response y = 10 a1 + a2
r = (y == 12).astype(float) # the verifier of 3*4
uniform = np.full(10, 0.1)
prob, w, A1, A2 = token_credit(uniform, uniform, r)
print('response r - V(x) A(s_1, a_1) A(s_2, a_2)')
for k in (12, 13, 52):
print(f'{k:8d} {w[k]:10.2f} {A1[k]:13.2f} {A2[k]:13.2f}')
S1 = np.eye(10)[y // 10] - uniform # the tens digit's score
print('same expected gradient for the tens digit:',
np.allclose(prob * w @ S1, prob * A1 @ S1))
print(f'variance: r - V(x) {prob @ w**2:.4f}, A(s_1, a_1) {prob @ A1**2:.4f}'
f', A(s_2, a_2) {prob @ A2**2:.4f}')response r - V(x) A(s_1, a_1) A(s_2, a_2)
12 0.99 0.09 0.90
13 -0.01 0.09 -0.10
52 -0.01 -0.01 0.00
same expected gradient for the tens digit: True
variance: r - V(x) 0.0099, A(s_1, a_1) 0.0009, A(s_2, a_2) 0.0090
y = np.arange(100) # the response y = 10 a1 + a2
r = (y == 12).astype(float) # the verifier of 3*4
uniform = np.full(10, 0.1)
prob, w, A1, A2 = token_credit(uniform, uniform, r)
print('response r - V(x) A(s_1, a_1) A(s_2, a_2)')
for k in (12, 13, 52):
print(f'{k:8d} {w[k]:10.2f} {A1[k]:13.2f} {A2[k]:13.2f}')
S1 = np.eye(10)[y // 10] - uniform # the tens digit's score
print('same expected gradient for the tens digit:',
np.allclose(prob * w @ S1, prob * A1 @ S1))
print(f'variance: r - V(x) {prob @ w**2:.4f}, A(s_1, a_1) {prob @ A1**2:.4f}'
f', A(s_2, a_2) {prob @ A2**2:.4f}')response r - V(x) A(s_1, a_1) A(s_2, a_2)
12 0.99 0.09 0.90
13 -0.01 0.09 -0.10
52 -0.01 -0.01 0.00
same expected gradient for the tens digit: True
variance: r - V(x) 0.0099, A(s_1, a_1) 0.0009, A(s_2, a_2) 0.0090
回答权重的方差是十位词元优势方差的十一倍。它可以裂项相消为 \(r - V(x) = \big(V(x, a_1) - V(x)\big) + \big(r - V(x, a_1)\big) = A(s_1, a_1) + A(s_2, a_2)\),且两项不相关(因为第二项在给定任意前缀下均值为零),于是方差直接相加:\(0.0099 = 0.0009 + 0.0090\)。每个词元的计分都背负着其余所有词元的噪声——\(T\) 个词元叠加 \(T\) 项噪声。
15.8.1.3 必需组件与可选组件
已知的确定性转移与单一终止奖励使本章许多部件不再必要:回答长度有限,因此 \(\gamma = 1\);无需学习转移模型,且生成可从任意前缀重启;不存在异轨策略自举,因此 15.4 节 的致命三元组不会出现。评论员也是可选的,因为回答权重本就无偏,而 14.8 节 的组均值无需网络即可充当基线,正如 RLOO (Ahmadian 等 2024年) 与 GRPO 的做法;若想获得逐词元信用分配,则需为每个前缀加价值头 (Ouyang 等 2022年),或像 VinePPO (Kazemnejad 等 2025年) 那样从前缀采样多条续写。真正不可或缺的是:带基线的计分函数、限制单步幅度的机制,以及防范奖励误差的保护(图 15.8.1)。
15.8.2 验证器、奖励模型及其漏洞
奖励要么来自人类比较拟合的奖励模型(15.3 节,在比较数据未覆盖处最不可靠),要么来自测试套件或精确匹配评分器等检查程序。直接针对检查程序训练——即基于可验证奖励的强化学习(RLVR)——正是近期推理模型的训练方式 (DeepSeek-AI 2025年)。验证器对它实际检查的性质是精确的,但这未必等同于人们真正想要的目标。
15.8.2.1 带 KL 惩罚的组更新
在 14.1 节 的验证器任务上,没有任何普通候选能答对 8*8 或 9*9,而第九个候选——对冲回答“one of 4, 12, 64 or 81”——在参考策略下的概率仅为每个普通候选的 \(e^{-4}\) 倍。sloppy_checker 只要回答包含正确答案就给分,因此它在每个提示上都给对冲回答发奖:
def sloppy_checker(task):
"""A lenient checker: 1 if the answer appears anywhere in response y."""
return lambda x, y: float(task.answers[x] in task.resp[y])
task = d2l.VerifierTask()
sloppy = sloppy_checker(task)
print(f'reference: exact score {task.success(task.pi_ref):.3f}, '
f'lenient score {task.success(task.pi_ref, sloppy):.3f}')reference: exact score 0.062, lenient score 0.065
def sloppy_checker(task):
"""A lenient checker: 1 if the answer appears anywhere in response y."""
return lambda x, y: float(task.answers[x] in task.resp[y])
task = d2l.VerifierTask()
sloppy = sloppy_checker(task)
print(f'reference: exact score {task.success(task.pi_ref):.3f}, '
f'lenient score {task.success(task.pi_ref, sloppy):.3f}')reference: exact score 0.062, lenient score 0.065
针对宽松验证器训练必然会找到这个对冲漏洞。15.3 节 的惩罚项 \(\beta\, D_{\textrm{KL}}\big(\pi(\cdot \mid x) \Vert \pi_{\textrm{ref}}(\cdot \mid x)\big)\) 可以直接折入奖励,给每条采样回答打分 \(r(x, y) - \beta \log\big(\pi_\theta(y \mid x) / \pi_{\textrm{ref}}(y \mid x)\big)\)。REINFORCE 估计依然无偏,因为对内部的 \(\log \pi_\theta\) 求导只额外贡献 \(-\beta\, \mathbb{E}[\nabla_\theta \log \pi_\theta] = 0\)。对于 \(T > 1\) 个词元,对数概率比是逐词元对数比之和,把终止奖励转化为每步奖励,因此每个词元的权重只需保留从该词元起的对数比(5c)。kl_group_step 将扣罚后的奖励交给 14.8 节 的组更新 d2l.group_step:
def kl_group_step(task, theta, K, reward, rng, beta, lr=2.0):
"""d2l.group_step with the reward r - beta log(pi(y|x) / pi_ref(y|x))."""
pi = task.policy(theta) # the policy that samples
def penalized(x, y):
return reward(x, y) - beta * np.log(pi[x, y] / task.pi_ref[x, y])
return d2l.group_step(task, theta, K, penalized, rng, lr)def kl_group_step(task, theta, K, reward, rng, beta, lr=2.0):
"""d2l.group_step with the reward r - beta log(pi(y|x) / pi_ref(y|x))."""
pi = task.policy(theta) # the policy that samples
def penalized(x, y):
return reward(x, y) - beta * np.log(pi[x, y] / task.pi_ref[x, y])
return d2l.group_step(task, theta, K, penalized, rng, lr)\(\beta\) 必须多大才能压住漏洞?最优解是按奖励倾斜的参考分布 \(\pi^\star(y \mid x) = \pi_{\textrm{ref}}(y \mid x)\, e^{r(x, y)/\beta} / Z(x)\)(15.3 节)。在 8*8 上宽松验证器只奖励对冲回答,因此它相对普通候选的几率从 \(e^{-4}\) 升至 \(e^{-4} e^{1/\beta}\):当且仅当 \(\beta < 1/4\) 时对冲回答更受青睐,而在 \(\beta = 0.2\) 时其概率已是普通候选的 \(e \approx 2.7\) 倍。在 2+2 和 3*4 上正确答案同样得奖,几率维持在 \(e^{-4}\),不存在阈值。
15.8.2.2 扫描并与闭式解对比
我们在五个 \(\beta\) 值上以 \(K = 32\) 训练 \(400\) 次更新,对最后 \(100\) 个策略取平均,将宽松得分、精确得分以及对冲回答的平均概率与倾斜最优解的对应数值并排打印(在偏好参数中,最优解即参考偏好加上奖励除以 \(\beta\)):
R = task.reward_table(sloppy) # sloppy(x, y) for every pair
def scores(task, pi, reward):
"""Expected reward, exact score, mean probability of the hedge."""
return task.success(pi, reward), task.success(pi), pi[:, -1].mean()
print('beta trained: lenient exact hedge optimum: lenient exact hedge')
for beta in (0.0, 0.1, 0.2, 0.3, 0.5):
rng, theta, avg = np.random.default_rng(0), task.theta_ref.copy(), 0
for step in range(400):
theta = kl_group_step(task, theta, 32, sloppy, rng, beta)
if step >= 300: # average the last 100 policies
avg = avg + task.policy(theta) / 100
row = '{:4.1f} {:18.2f} {:6.2f} {:6.2f}'.format(
beta, *scores(task, avg, sloppy))
if beta > 0: # the tilted optimum in preferences
pi_star = task.policy(task.theta_ref + R / beta)
row += '{:18.2f} {:6.2f} {:6.2f}'.format(*scores(task, pi_star, sloppy))
print(row)beta trained: lenient exact hedge optimum: lenient exact hedge
0.0 1.00 0.50 0.50
0.1 0.99 0.50 0.49 0.99 0.49 0.50
0.2 0.60 0.48 0.12 0.60 0.47 0.14
0.3 0.44 0.40 0.04 0.43 0.39 0.04
0.5 0.25 0.23 0.01 0.27 0.25 0.01
R = task.reward_table(sloppy) # sloppy(x, y) for every pair
def scores(task, pi, reward):
"""Expected reward, exact score, mean probability of the hedge."""
return task.success(pi, reward), task.success(pi), pi[:, -1].mean()
print('beta trained: lenient exact hedge optimum: lenient exact hedge')
for beta in (0.0, 0.1, 0.2, 0.3, 0.5):
rng, theta, avg = np.random.default_rng(0), task.theta_ref.copy(), 0
for step in range(400):
theta = kl_group_step(task, theta, 32, sloppy, rng, beta)
if step >= 300: # average the last 100 policies
avg = avg + task.policy(theta) / 100
row = '{:4.1f} {:18.2f} {:6.2f} {:6.2f}'.format(
beta, *scores(task, avg, sloppy))
if beta > 0: # the tilted optimum in preferences
pi_star = task.policy(task.theta_ref + R / beta)
row += '{:18.2f} {:6.2f} {:6.2f}'.format(*scores(task, pi_star, sloppy))
print(row)beta trained: lenient exact hedge optimum: lenient exact hedge
0.0 1.00 0.50 0.50
0.1 0.99 0.50 0.49 0.99 0.49 0.50
0.2 0.60 0.48 0.12 0.60 0.47 0.14
0.3 0.44 0.40 0.04 0.43 0.39 0.04
0.5 0.25 0.23 0.01 0.27 0.25 0.01
在 \(\beta = 0\) 时,策略在宽松验证器下拿满分,但在精确评估下仅得 \(0.50\),在 8*8 和 9*9 上把全部概率都押在了对冲回答上。在 \(\beta = 0.1\) 与 \(0.2\) 时对冲回答仍占上风;跨过 \(1/4\) 后便被压住——在 \(\beta = 0.3\) 时,它在 8*8 上的概率约为每个普通候选的一半,正如 \(e^{-4} e^{1/0.3} \approx 0.5\) 所预测。代价是正常学习受阻:在 \(\beta = 0.5\) 时精确得分跌至约四分之一。训练结果与闭式最优解相差在约 \(0.02\) 以内,存在微小系统性差距:靠近 \(\pi^\star\) 时组内带罚奖励趋于相等,标准化反而在迭代本该停稳的地方放大了步幅。惩罚只是在每个 \(\beta\) 上给漏洞标了价,却从未真正堵住漏洞。
15.8.3 后训练更新
15.8.3.1 面向过时样本的概率比
此前每次更新都只用一次新鲜采样组,但大规模后训练并非如此:负责生成回答的推理引擎往往与训练器使用不同的算子内核与数值精度,而且每批数据要支撑多次梯度更新。样本来自较旧策略 \(\pi_{\theta_{\textrm{old}}}\),因此词元 \(t\) 按 15.2 节 的方式以比值 \(\rho_t = \pi_\theta(a_t \mid s_t) / \pi_{\theta_{\textrm{old}}}(a_t \mid s_t)\) 加权并裁剪。整条回答对应连乘比值 \(W\) 及其几何平均 \(\bar\rho\):
\[W = \prod_{t=1}^{T} \rho_t, \qquad \bar\rho = W^{1/T} = \exp\Big(\frac{1}{T} \sum_{t=1}^{T} \log \rho_t\Big). \tag{15.8.2}\]
连乘积 \(W\) 是精确校正,但它的对数是 \(T\) 个带噪项之和,在长回答上会跨越许多个数量级。组序列策略优化(GSPO)改为裁剪 \(\bar\rho\)——每条回答仅一个尺度不随长度膨胀的标量 (Zheng 等 2025年)。
15.8.3.2 非对称裁剪区间
比值空间里的固定宽度区间在概率空间里允许的改动悬殊:当 \(\epsilon_{\textrm{clip}} = 0.2\) 时,概率为 \(0.01\) 的词元涨过 \(0.012\) 就不再受益,而概率为 \(0.6\) 的词元可以涨到 \(0.72\)。在包含数万个多为罕见词元的词表上,有用的罕见词元增长缓慢、策略熵不断下跌;因此 DAPO 单独抬高上界至 \(1 + \epsilon_{\textrm{high}}\)(取 \(\epsilon_{\textrm{high}} = 0.28\))(Yu 等 2025年)(6)。
15.8.3.3 组相对策略优化
组相对策略优化(GRPO)(Shao 等 2024年) 将上述部件拼装在一起。它从 \(\pi_{\theta_{\textrm{old}}}\) 为每个提示采样 \(K\) 条回答,并赋予回答 \(j\) 的每个词元 14.8 节 的标准化权重 \(\hat{A}_j = (r_j - \bar{r}) / (\sigma_r + 10^{-8})\)(\(\bar{r}\) 与 \(\sigma_r\) 为组内奖励均值与标准差)。随后在同一组上多轮最大化
\[ \begin{aligned} &\frac{1}{K} \sum_{j=1}^{K} \frac{1}{T_j} \sum_{t=1}^{T_j} \Big[ \min\big(\rho_{j,t}\, \hat{A}_j,\ \textrm{clip}(\rho_{j,t}, 1 - \epsilon_{\textrm{clip}}, 1 + \epsilon_{\textrm{clip}})\, \hat{A}_j\big) \\ &\qquad\qquad\qquad - \beta\, k_3(j, t) \Big], \end{aligned} \]
其中 \(T_j\) 是回答 \(j\) 的长度,\(k_3 = \pi_{\textrm{ref}}/\pi_\theta - \log(\pi_{\textrm{ref}}/\pi_\theta) - 1\) 在采样词元处求值。取最小值在样本比值越出有利一侧边界后撤去其梯度。裁剪相对的是采样策略,用于限制单次更新幅度;KL 惩罚相对的则是冻结参考策略,用于改变最优解。
grpo_step 在每条回答仅含一个词元的验证器任务上实现该目标。在 num_epochs 轮遍历中,每轮先计算相对采样策略的比值,筛选出裁剪项仍依赖 \(\theta\) 的样本(live),再执行一步梯度上升;\(\rho\,\hat{A}\) 与 \(-\beta k_3\) 的梯度分别为 \(\rho\,\hat{A}\) 和 \(-\beta(1 - \pi_{\textrm{ref}}/\pi_\theta)\) 乘以计分 \(\mathbf{e}_y - \pi_\theta(\cdot \mid x)\):
def grpo_step(task, theta, K, reward, rng, beta=0.04, epsilon=0.2,
num_epochs=4, lr=2.0):
"""One group of K responses per prompt, reused for num_epochs clipped
ascent steps with the k3 penalty; returns theta and each epoch's ratios."""
pi_old, n = task.policy(theta), len(task.resp)
ys = np.stack([rng.choice(n, K, p=p) for p in pi_old]) # (prompts, K)
A = np.stack([d2l.standardize(np.array([reward(x, y) for y in ys[x]]))
for x in range(len(ys))])
rows, onehot, ratios = np.arange(len(ys))[:, None], np.eye(n)[ys], []
for _ in range(num_epochs):
pi = task.policy(theta)
rho = pi[rows, ys] / pi_old[rows, ys]
live = np.where(A > 0, rho < 1 + epsilon, rho > 1 - epsilon)
u = live * A * rho - beta * (1 - task.pi_ref[rows, ys] / pi[rows, ys])
theta = theta + lr * np.einsum('xk,xkn->xn', u, onehot - pi[:, None]) / K
ratios.append(rho)
return theta, ratiosdef grpo_step(task, theta, K, reward, rng, beta=0.04, epsilon=0.2,
num_epochs=4, lr=2.0):
"""One group of K responses per prompt, reused for num_epochs clipped
ascent steps with the k3 penalty; returns theta and each epoch's ratios."""
pi_old, n = task.policy(theta), len(task.resp)
ys = np.stack([rng.choice(n, K, p=p) for p in pi_old]) # (prompts, K)
A = np.stack([d2l.standardize(np.array([reward(x, y) for y in ys[x]]))
for x in range(len(ys))])
rows, onehot, ratios = np.arange(len(ys))[:, None], np.eye(n)[ys], []
for _ in range(num_epochs):
pi = task.policy(theta)
rho = pi[rows, ys] / pi_old[rows, ys]
live = np.where(A > 0, rho < 1 + epsilon, rho > 1 - epsilon)
u = live * A * rho - beta * (1 - task.pi_ref[rows, ys] / pi[rows, ys])
theta = theta + lr * np.einsum('xk,xkn->xn', u, onehot - pi[:, None]) / K
ratios.append(rho)
return theta, ratios我们将每提示 \(32\) 条回答的一组数据复用四轮,打印每轮的比值范围与越出 \([0.8, 1.2]\) 区间的比例,并与同一组上只更新一步的结果对比:
epsilon = 0.2 # grpo_step's half-width of the band
theta, ratios = grpo_step(task, task.theta_ref, 32, task.verify,
np.random.default_rng(0), epsilon=epsilon)
for epoch, rho in enumerate(ratios, 1):
print(f'epoch {epoch}: ratios from {rho.min():.2f} to {rho.max():.2f}, '
f'{np.mean(abs(rho - 1) > epsilon):.0%} outside the band')
theta_1, _ = grpo_step(task, task.theta_ref, 32, task.verify,
np.random.default_rng(0), num_epochs=1)
print(f'exact score: reference {task.success(task.pi_ref):.3f}, one epoch '
f'{task.success(task.policy(theta_1)):.3f}, four epochs '
f'{task.success(task.policy(theta)):.3f}')epoch 1: ratios from 1.00 to 1.00, 0% outside the band
epoch 2: ratios from 0.81 to 1.97, 5% outside the band
epoch 3: ratios from 0.74 to 2.23, 14% outside the band
epoch 4: ratios from 0.75 to 2.39, 30% outside the band
exact score: reference 0.062, one epoch 0.111, four epochs 0.137
epsilon = 0.2 # grpo_step's half-width of the band
theta, ratios = grpo_step(task, task.theta_ref, 32, task.verify,
np.random.default_rng(0), epsilon=epsilon)
for epoch, rho in enumerate(ratios, 1):
print(f'epoch {epoch}: ratios from {rho.min():.2f} to {rho.max():.2f}, '
f'{np.mean(abs(rho - 1) > epsilon):.0%} outside the band')
theta_1, _ = grpo_step(task, task.theta_ref, 32, task.verify,
np.random.default_rng(0), num_epochs=1)
print(f'exact score: reference {task.success(task.pi_ref):.3f}, one epoch '
f'{task.success(task.policy(theta_1)):.3f}, four epochs '
f'{task.success(task.policy(theta)):.3f}')epoch 1: ratios from 1.00 to 1.00, 0% outside the band
epoch 2: ratios from 0.81 to 1.97, 5% outside the band
epoch 3: ratios from 0.74 to 2.23, 14% outside the band
epoch 4: ratios from 0.75 to 2.39, 30% outside the band
exact score: reference 0.062, one epoch 0.111, four epochs 0.137
第一轮所有比值均为 \(1\),因为策略尚未移动。仅走一步后,正确答案的比值就已超过 \(1.5\):裁剪并不硬性限死单步幅度,只是在越过区间后不再奖励继续增长。越界比例随后上升,且在几乎每组上第四轮都高于第二轮。在四十组测试中,四轮复用最终的精确得分每次都高于单步更新。
\(k_3\) 项对策略的约束方式与折入奖励的惩罚截然不同。尽管它在 \(\pi_\theta\) 下的期望等于 \(D_{\textrm{KL}}(\pi_\theta \Vert \pi_{\textrm{ref}})\),但在固定样本下直接对它求导得到的却是前向散度 \(D_{\textrm{KL}}(\pi_{\textrm{ref}} \Vert \pi_\theta)\) 的期望梯度 (Tang 和 Munos 2025年)(5)。15.3.3.5 节 区分的两种散度方向在漏洞上差异悬殊:在 8*8、\(\beta = 0.5\) 时,反向最优解将对冲概率压在 \(0.017\),前向最优解却放任其高达 \(0.50\)。前向散度惩罚的是忽视参考策略的普通候选,而非把概率移向参考策略极少选择的动作。
两个广为流传的变体微调了这些选择。DAPO 去掉 KL 惩罚、抬高裁剪上界,并丢弃组内奖励全相等的样本组 (Yu 等 2025年);Dr. GRPO 则去掉了除以 \(\sigma_r\) 和除以回答长度的操作(14.8.3.4 节)(Liu 等 2025年)。
15.8.3.4 直接偏好优化
反过来读倾斜最优解,即可由策略反推出奖励:
\[r(x, y) = \beta \log \frac{\pi^\star(y \mid x)}{\pi_{\textrm{ref}}(y \mid x)} + \beta \log Z(x), \tag{15.8.3}\]
也就是说,每条策略在相差一个比较看不见的提示项的意义下,都唯一定义了以它为最优解的奖励。将其代入 Bradley-Terry 似然,奖励拟合便直接化为策略本身的分类损失,既无需采样也无需奖励模型——这就是直接偏好优化(DPO)(Rafailov 等 2023年)。它的数据是一份固定的成对偏好集,因此也继承了 15.7 节 中的全部离线问题。
本节一切都建立在单轮生成与单一终止奖励之上,使问题退化为整条回答上的上下文赌博机(14.4 节);一旦引入工具调用、环境反馈或多轮对话,转移核便会回归,评论员与跨步信用分配问题也随之重现。语言模型部分将讨论大规模后训练,15.9 节 则汇总了各类变体与实践项目。
本章始于一个耗时几十万步的倒立摆。在 CartPole 上,一步评论员未能省步,每批四轮 PPO 将步数减半,DQN 需要三万五千到四万五千步;在 Pendulum 上,柔性演员–评论员只需几千步,学习世界模型则缩至几百步(以算力买单);离线学习器一步新交互也不做,而单组四轮更新用相同样本把策略推得更远。每一份样本节省都建立在一个可能出错的估计之上——评论员、过时批次、模型、日志或验证器。
15.8.4 小结
一条回答即一条词元轨迹,两种视角导出同一个梯度。单一终止得分赋予每个词元相同权重 \(r - b(x)\),其方差等于各词元优势方差之和;前缀价值可给出逐词元信用分配(代价是引入评论员或重启采样),而由于回答权重本身无偏,评论员并非必需。KL 惩罚按倾斜最优解预测的速率(含临界阈值)为验证器漏洞定价。GRPO 结合了组权重、裁剪概率比与 \(k_3\) 惩罚,而后者的梯度对应前向散度,几乎无法遏制对冲漏洞。
15.8.5 练习
- 轨迹中的工具输出。调用工具的模型先输出词元 \(y^{(1)}\),接收不依赖 \(\theta\) 的工具输出 \(o \sim P_{\textrm{tool}}(\cdot \mid x, y^{(1)})\),再继续输出词元 \(y^{(2)}\)。验证器对 \(\tau = (x, y^{(1)}, o, y^{(2)})\) 统一打分一次,奖励为 \(r(\tau)\)。
- 写出 \(\tau\) 的概率及其对数的梯度。哪些词元贡献了计分项?
- 如果训练循环在整个序列上计算对数概率,就会多出 \(\big(r(\tau) - b(x)\big)\, \nabla_\theta \log \pi_\theta(o \mid x, y^{(1)})\) 一项(用模型自身对工具输出的概率求导)。证明即使权重为常数,该项期望一般也不为零,并指出“计分均值为零”论证中哪一步失效了。这一多余项实际上在训练模型做什么?
- 两位数回答。设 15.8.1.2 节 中的两位数字分别采自分布 \(\mathbf{p}_1\) 和 \(\mathbf{p}_2\)(各自为独立偏好参数的 softmax),且验证器仅对正确答案支付 \(1\)。
- 证明回答权重 \(r - V(x)\) 与词元优势对两个位置的偏好参数给出相同的期望梯度。哪一个条件期望保证了两者一致?
- 证明 \(A(s_1, a_1)\) 与 \(A(s_2, a_2)\) 不相关,并写出 \(T\) 个词元回答的推广结论。
- 在第一位选数字 \(1\) 与第二位选数字 \(2\) 均赋予概率 \(0.9\)(其余每个数字概率 \(1/90\))的策略上调用
token_credit。此时用 \(A(s_1, a_1)\) 替换回答权重把十位数字更新的方差降低了多少,为什么降幅小于均匀策略?
- 对冲回答的两个阈值。设 \(\pi^\star\) 是奖励
sloppy与参考task.pi_ref对应的倾斜最优解。- 在
8*8与9*9上,对冲回答是sloppy唯一奖励的回答。将其在 \(\pi^\star\) 下的概率写成 \(\beta\) 的函数。在什么 \(\beta\) 处它与其余八个回答各自等概率?又在什么取值处它占到总概率的一半?哪一个是正文提到的阈值? - 在
2+2与3*4上,正确答案与对冲回答均获奖励。当 \(\beta \to 0\) 时,\(\pi^\star\) 给对冲回答分配多大概率? - 在 \(\beta = 0\) 时,训练在
2+2和3*4上几乎未给对冲回答分配质量,尽管两个得奖回答间的任何概率分配都最大化无正则目标。d2l.group_step更新中的哪项性质选定了训练最终抵达的分配?
- 在
- [code] 有限实例上的 DPO。● 设同一提示下采自
task.pi_ref的两个回答之间的偏好服从以sloppy为奖励的 Bradley-Terry 模型。记 \(y_w\) 与 \(y_l\) 分别为胜出和落败回答,令 \(h_\theta(y) = \log\big(\pi_\theta(y \mid x) / \pi_{\textrm{ref}}(y \mid x)\big)\)。- 将 式 15.8.3 代入 Bradley-Terry 模型,证明单对样本的负对数似然为 \(-\log \sigma\big(\beta\, h_\theta(y_w) - \beta\, h_\theta(y_l)\big)\),其中 \(\sigma\) 为逻辑函数。为什么 \(Z(x)\) 没有出现?
- 证明在无限多对样本下,期望损失由倾斜最优解最小化。这对 3a 的阈值意味着什么?
- 为每个提示抽取 \(1000\) 对带标签样本,从
task.theta_ref出发以步长 \(10\) 在偏好表上做梯度下降,在 \(\beta = 0.5\) 下最小化平均损失。在五个种子上报告 \(200\)、\(2000\) 和 \(20000\) 步后每个提示的对冲概率。在对冲回答从未输过一次比较的提示上发生了什么,为什么 \(\beta\) 没能阻止它?
- 作为损失项的 KL 惩罚。●● GRPO 在每个采样词元上减去 \(\beta k_3\) 并在词元固定时对其求导 (Shao 等 2024年);Tang 和 Munos (2025年) 分析了此类损失实际优化的目标。
对单词元回答,记 \(h = \log\big(\pi_\theta(y \mid x) / \pi_{\textrm{ref}}(y \mid x)\big)\),比较三种损失 \(k_1 = h\)、\(k_2 = h^2 / 2\) 与 \(k_3 = e^{-h} + h - 1\)。证明对 \(y \sim \pi_\theta\),\(k_1\) 的期望梯度为零,\(k_2\) 的期望梯度为 \(\nabla_\theta D_{\textrm{KL}}(\pi_\theta \Vert \pi_{\textrm{ref}})\),\(k_3\) 的期望梯度为 \(\nabla_\theta D_{\textrm{KL}}(\pi_{\textrm{ref}} \Vert \pi_\theta)\)。
在前向惩罚 \(\beta\, D_{\textrm{KL}}(\pi_{\textrm{ref}} \Vert \pi)\) 下,最优解为 \(\pi(y) = \beta\, \pi_{\textrm{ref}}(y) / \big(m - r(y)\big)\),其中乘子 \(m > \max_y r(y)\) 使概率和为 1(7a)。在
8*8与奖励sloppy上,对 \(\beta \in \{0.1, 0.25, 0.5\}\) 数值求解 \(m\),将对冲概率与倾斜最优解对比。两者的差距如何依赖 \(\beta\)?对 \(T\) 个词元的回答,记 \(h_t\) 为第 \(t\) 个词元的对数比,利用 式 15.8.1 证明
\[\nabla_\theta D_{\textrm{KL}}\big(\pi_\theta(\cdot \mid x) \Vert \pi_{\textrm{ref}}(\cdot \mid x)\big) = \mathbb{E}\Big[\sum_{t=1}^{T} \nabla_\theta \log \pi_\theta(a_t \mid s_t) \sum_{t'=t}^{T} h_{t'}\Big]. \tag{15.8.4}\]
逐词元 \(k_2\) 损失之和漏掉了哪些项?为什么像
kl_group_step那样把惩罚折入奖励可以避免这一遗漏?
- 非对称裁剪区间。某词元在采样策略下的概率为 \(0.01\)。假设每批更新都恰好把它的概率放大 \(1 + \epsilon_{\textrm{high}}\) 倍(即裁剪停止奖励增长的边界,见 15.8.3.2 节),且下一批由更新后的策略采样。
- 将概率从 \(0.01\) 提高到 \(0.5\),当 \(\epsilon_{\textrm{high}} = 0.2\) 时需要多少批,当 \(\epsilon_{\textrm{high}} = 0.28\) 时需要多少批?
- 在二动作问题中,另一动作初始概率为 \(0.99\)。计算经过这样一批更新后它的比值。究竟是区间的哪一侧、作用在哪个动作上,限制了罕见动作提升概率的速度?
- 在二动作情形下,上裁剪仅在 \((1 + \epsilon_{\textrm{high}})\, p < 1\) 时才限制高概率动作(概率 \(p\))的增长。在什么 \(p\) 范围内,将 \(\epsilon_{\textrm{high}}\) 从 \(0.2\) 提到 \(0.28\) 也会让高概率动作增长更快,这对熵有何影响?为什么在拥有数万个多为罕见词元的语言模型上,同样的改动反而能维持更高的熵?
- 长度归一化比值。● GSPO (Zheng 等 2025年) 用 式 15.8.2 的几何平均 \(\bar\rho = W^{1/T}\) 取代逐词元比值作为权重和裁剪对象。将采样策略下的逐词元对数比 \(\log \rho_t\) 建模为独立同分布、均值 \(-d\)、方差 \(v\)(其中 \(d\) 为逐词元散度 \(D_{\textrm{KL}}(\pi_{\theta_{\textrm{old}}} \Vert \pi_\theta)\))。
- 证明 \(\log W\) 的均值为 \(-d T\)、方差为 \(vT\),而 \(\log \bar\rho\) 的均值为 \(-d\)、方差为 \(v / T\)。
- 证明 \(\mathbb{E}[\bar\rho] \leq 1\) 且随 \(T \to \infty\) 有 \(\mathbb{E}[\bar\rho] \to e^{-d}\)。重要性权重 \(W\) 对回答的任意函数 \(f\) 满足 \(\mathbb{E}_{\pi_{\theta_{\textrm{old}}}}[W f] = \mathbb{E}_{\pi_\theta}[f]\);\(\bar\rho\) 是否满足?
- GSPO 将 \(\bar\rho\) 裁剪到 \([1 - 3 \cdot 10^{-4}, 1 + 4 \cdot 10^{-4}]\),而其 GRPO 基线将逐词元比值裁剪到 \([1 - 0.2, 1 + 0.27]\)。用 (a) 解释为什么序列级区间必须窄得多才会生效。