Reinforcement learning · October 2026强化学习 · 2026 年 10 月強化学習 · 2026年10月

PPO, Along a Long-Horizon TrajectoryPPO:沿一条长程轨迹看训练長い実行軌跡から理解するPPO

Follow one code repair from tool calls to parameter updates: what the Actor, Reference, Reward Model and Critic see, predict and learn.从一次代码修复出发,看 Actor、Reference、奖励模型与 Critic 分别读入什么、输出什么,以及参数如何更新。一つのコード修正を、ツール呼び出しからパラメータ更新までたどる。Actor、Reference、報酬モデル、Criticは何を読み、何を出力し、何を学ぶのか。

1 The complete training loop

A coding agent reads files, calls tools, and edits code. Its actions and the tool responses form a trajectory. PPO uses the outcome of that execution to adjust the probabilities of actions generated along the way.

In reinforcement learning from human feedback (RLHF) with a reward model, the Actor generates actions, the RM scores the completed attempt, the Critic predicts future return from the current context, and the Reference supplies a fixed policy baseline. Rewards and value predictions enter advantage estimation, producing the targets used to train Actor and Critic. A—D in the overview correspond to the four modules below.

The complete training loop
A · Before PPO
ExamplesSupervised fine-tuningActor + ReferenceTwo copies of the initial policyPreference pairsTrain RM
B · Collect trajectories
C · Rewards and advantages
D · Parameter updates
ActorCurrent policy πoldTool environmentFiles · shell · testsTrajectory recordTask + actions + observationsRMFixed weightsReferenceFixed weightsCriticReads each history prefixConstruct rewards rtTerminal score + KL penaltyGAEPropagate feedback backwardUpdate ActorClipped PPO objectiveUpdate CriticFit return targets Ĝt
Tool calls
Observations
Complete execution
Prefix + token
Prefix ht
Score R
Reference probabilities
rt
Values Vt
Advantages At
Return targets Ĝt
Sampled tokens + old probabilities
Updated Actor collects the next batch
Updated value predictions
Saved log πold
Figure 1 · A prepares models; B collects trajectories; C computes rewards and advantages; D updates Actor and Critic. RM and Reference stay fixed during PPO. Nodes link to the corresponding sections.

2 A · Prepare the policy and reward model

Training usually starts with an existing language model and supervised fine-tuning (SFT): successful demonstrations teach it to produce appropriate actions in context. PPO then lets the policy network, the Actor, try new executions and learn from their outcomes. [1]

After SFT, keep two copies of the policy: one becomes the Actor and continues learning; the other is frozen as the Reference. The Reference computes probabilities for generated tokens, helping constrain how far the Actor moves from its initial policy.

Our running example repairs an amount-summing script: add the strings "0.10" and "0.20" exactly and print 0.30. The trajectory and scores are constructed for illustration.

First, prepare two complete executions. A uses Decimal and passes the tests; B retains the floating-point output. An annotator selects A, providing the label “A is preferred to B.” To train a reward model (RM), feed “task + execution A” and “task + execution B” separately into the same model, obtaining scores rA and rB.

A · How the reward model learns
Task + complete attempt ADecimal sum → output 0.30
Task + complete attempt Bfloat sum → rounding error
One shared RMLanguage model + scalar head
Two forward passesrA, rB
Preference label: A over B
Preference loss−log σ(rA − rB)
Backpropagation · update RM weights
Figure 2 · Two complete attempts pass through the same RM. Preference labels supervise score ordering; gradients update the RM. The trained RM stays fixed during PPO.
LRM=−log⁡σ(rA−rB)

The sigmoid function σ converts the score difference into a preference probability. Minimizing this loss encourages a higher relative score for A. Many such pairs teach the RM to evaluate new executions. Annotators supply the ordering; the RM learns its scoring scale. The RM commonly consists of a language-model backbone and a scalar head that outputs one score. [1]

3 B · Let the Actor make an attempt

The input uses JSONL, one JSON object per line. The original script converts amounts to float, producing 0.30000000000000004. The Actor needs to find the problem, parse amount strings with Decimal, and format the result to two decimal places.

We use four roles in this reinforcement learning from human feedback (RLHF) setup. A rollout is an attempt made by the current Actor in its environment. It generates tokens—the encoded units of text—to form tool calls and a final response. File contents and test logs returned by the environment become context for subsequent generation.

B · One repair, through Actor and tools
Task: sum "0.10" and "0.20", then print 0.30
Actor
Tool environment
Read the scriptcat summarize.py
Find a float-based sumfloat(row["amount"])
Run the testpytest -q
Test fails0.30000000000000004
Apply the patchDecimal(row["amount"])
File updatedformat(total, ".2f")
Test againpytest -q
Test passes0.30
Submit the fix and test result
RM reads the completed attempt: R = 8
Figure 3 · An illustrative repair. Tool responses join the history used for the next call. The RM scores the completed record.

The Actor generates actions. The RM reads the task and completed record to provide a final score. At each generation position, the Critic reads the prefix available at that moment and predicts the return ahead. A fixed Reference model computes the probability of the generated token in the same context, providing a reference for how far the policy has moved from its starting point.

In this example, “tests passed” is a tool observation; the RM supplies the final reward. With a reliable automated verifier, its result can instead define the reward directly and replace the RM.

A training mask identifies positions generated by the Actor. File contents and test logs remain in the input to inform its decisions; the policy loss applies only to generated tokens. The Critic's predictions can be computed in a batch after collection, with each prediction still restricted to its corresponding prefix.

4 C · How the Critic learns from outcomes

The value network, or Critic, predicts the average future return when the current Actor continues from a given context. Suppose four outcomes for the same task are equally likely and receive scores of 2, 4, 6, and 8 from a fixed RM. Their mean is 5. The Critic learns that expectation from observed outcomes. These numbers use an illustrative scale.

A return accumulates rewards from a particular position onward. To train the Critic, finish an attempt and pair earlier history prefixes with their return targets. Generalized Advantage Estimation (GAE) constructs these targets from rewards and value predictions; the diagram traces that data flow.

C · Turning outcomes into Critic training data
Completed repair τ
RMFixed weights
R = 8
Prefixes at two positionsh₁: before repair · h₂: after repair
CriticPredict future returns
Current predictionsV(h₁) = 5
V(h₂) = 7
GAE · Build targetsĜt = At + Vt
Return targets ĜtĜ₁ = 8 · Ĝ₂ = 8
Value regression lossmean (Vφ(ht) − Ĝt)²
Backpropagation · update Critic
At goes to the Actor update
A₁ = 3 · A₂ = 1
Figure 4 · One execution supplies several prefix–return pairs. With terminal-only R=8, β=0 and γ=λ=1, both targets are 8; the advantages are 3 and 1. The targets stay fixed for this regression update.

A Critic also commonly uses a language-model backbone with a scalar head. InstructGPT initialized its value function from the RM, then trained it on trajectory returns. It reused the initial parameters; subsequent supervision came from the return targets associated with each prefix. [1]

The Critic pairs each prefix with its return target. A prediction of 5 against a target of 8 gives a squared error of 9. Backpropagation and an optimizer adjust its trainable parameters to reduce that error. Full fine-tuning updates both the backbone and the scalar head. Targets are fixed for this update, and this loss does not update the RM.

LV = mean [Vφ(ht) − Ĝt]2

φ denotes the Critic's parameters. With repeated outcomes, regression learns an average return. Its context-dependent baseline helps reduce sampling noise in the policy gradient. Returns alone can also train a policy; a suitable value prediction makes updates from limited samples more stable. [3]

The RM learns a scoring criterion from preferences; the Critic learns an expectation from returns. During PPO, the RM is usually fixed while the Critic continues learning. As the Actor produces high-scoring executions more often, the Critic's prediction should rise even though the scoring criterion stays the same.

A common RLHF-PPO setup combines the final RM score with a reference penalty. At generation position t, a commonly used sampled form is:

rt = −β [log πold(at | ht) − log πref(at | ht)] + 𝟙t=T R

Here ht is the prefix, at the generated token, and T the final generation position. R is added only at the end; β sets the strength of the reference penalty. The expected log-probability difference over the action distribution is a KL divergence. [1]

Generalized Advantage Estimation (GAE) combines rewards and value predictions, working backward to estimate an advantage at each generation position:

δt = rt + γ(1 − dt)Vt+1 − Vt
At = δt + γλ(1 − dt)At+1
Ĝt = At + Vt

δ is the one-step prediction error. γ discounts future rewards, and λ controls how much later advantage estimates contribute. d=1 marks genuine task termination. Ĝ is the Critic's return target. Here t indexes generation decisions; tool observations enter the next decision's context. [2]

Take the example's final score R=8, with β=0, γ=λ=1, and a reward only at genuine termination. A starting prediction of V=5 gives an advantage of +3. At a later position after the repair, a prediction of V=7 gives +1. Both return targets are 8; their differences from the local expectations are different.

5 D · How the Actor updates probabilities

The Actor uses advantages to adjust the probabilities of sampled actions. Call the policy that collected this batch πold, and the policy being updated πθ:

D · How the Actor learns from a batch
One fixed batchPrefix ht · sampled token at
Actor being optimizedπθ
Recompute probabilitiesπθ(at | ht)
Saved collection probabilitiesπold(at | ht)
Probability ratio ρtπθ / πold
Advantages AtGAE → At
Clipped PPO loss
Backpropagation · update Actor weights θ
Figure 5 · Recompute probabilities for sampled tokens and compare them with saved collection probabilities. Advantages provide the update direction; clipping limits incentives for large changes. The updated Actor collects a new batch.
ρt = πθ(at | ht) / πold(at | ht)
Lπ = −mean min [ρtAt, clip(ρt, 1 − ε, 1 + ε)At]

A positive advantage encourages a higher probability; a negative advantage points in the opposite direction. clip bounds the probability ratio inside the objective, limiting the incentive to push an update further. The full batch also influences the actual parameter update. [4]

The old policy and the Reference serve different purposes. The old policy anchors this batch's update and changes with later batches. The Reference usually stays fixed at the SFT starting point. Old log probabilities can be saved with trajectories, without keeping a fifth model resident in memory.

6 What long trajectories make difficult

A successful execution can contain investigation, useful edits, and unnecessary actions. Advantage estimation passes terminal feedback back through those positions, but the feedback remains noisy. Errors in value predictions also enter the advantages. As the Actor changes, the Critic needs to keep up.

Tool logs add another concern: trajectory length. An implementation must specify which positions participate in advantage recursion and how often discounting applies. Masking the logs out of the policy loss does not establish those rules. Computational chunks must carry the next value and advantage across their boundaries; genuine termination and truncation require different treatment.

The scoring criterion must track the intended outcome. An RM that favors polished completion claims may reward an execution that never fixes the program. Tests, preference data, and held-out evaluations should cover the actual deliverable. Large policy updates can also make collected trajectories stale, while an excessive KL penalty limits exploration. Learning rates, clipping, scoring quality, and sampling cost need to be considered together. [5]

7 What GRPO and DPO change

GRPO generates a group of answers for each task and uses the group's mean and standard deviation to compute relative advantages, removing the Critic. The original method retains an RM and a reference model; verifiable rewards can also replace the RM. Multiple executions per task cost more to sample, and equal scores throughout a group provide no relative reward differences. [6]

Standard offline DPO trains directly on existing “A is preferred to B” data. It retains an Actor and a reference model while removing the separate RM, Critic, and online sampling-and-scoring loop. It rewrites KL-regularized reward optimization as an objective over policy probabilities: reward can be expressed using a policy-to-reference log-probability ratio, and the shared normalization term cancels when comparing two answers to the same prompt. Preference-data quality and coverage become central. [7]

For coding tasks, the choice also depends on execution cost, the reliability of automated verification, and the availability of paired preferences. Terminal-RSI uses verifier rewards with PPO and studies long-trajectory advantage estimation and Critic handoff. It has no separate preference RM.

1 先看完整的训练循环

代码 Agent 读文件、调用工具、修改程序;这些动作与工具返回共同组成一条轨迹。PPO 利用整次执行的结果,调整沿途生成动作的概率。

在采用奖励模型的人类反馈强化学习(RLHF)中,Actor 生成动作,RM 评价完整结果,Critic 预测从当前上下文继续执行的回报,Reference 提供固定的策略参照。一次执行结束后,奖励与价值预测经过优势估计,分别成为 Actor 和 Critic 的训练目标。图中的 A—D 对应下文四个模块。

训练全流程
A · 学习开始前
操作示范监督微调 SFTActor + Reference同一初始策略的两份参数成对偏好训练 RM
B · 执行任务
C · 奖励与优势
D · 参数更新
Actor当前策略 πold工具环境文件 · Shell · 测试轨迹记录任务 + 动作 + 观察RM固定参数Reference固定参数Critic读取每个历史前缀构造奖励 rt终点得分 + KL 约束GAE按位置回传反馈更新 ActorPPO 裁剪目标更新 Critic拟合回报目标 Ĝt
工具调用
工具返回
完整执行
前缀 + token
前缀 ht
得分 R
参考概率
rt
价值 Vt
优势 At
回报目标 Ĝt
已采样 token 与旧概率
新 Actor 继续采样
更新后的价值预测
保存的 log πold
图 1 · A 准备模型,B 收集轨迹,C 计算奖励与优势,D 更新 Actor 与 Critic。RM 与 Reference 在 PPO 中固定。节点可跳转至对应章节。

2 A · 准备策略与奖励模型

训练通常从已有语言模型开始,先做监督微调(SFT):给它合格的操作示范,提高相应上下文下生成这些操作的概率。PPO 随后让策略网络 Actor 自己尝试,从新结果中学习。[1]

SFT 后保留两份相同的策略参数:一份成为继续学习的 Actor,另一份固定为 Reference。Reference 对已生成的 token 计算概率;PPO 用这组概率约束 Actor 偏离初始策略的程度。

下面以修复金额汇总脚本为例:把字符串金额 "0.10" 与 "0.20" 精确相加,输出 0.30。轨迹与分数采用教学构造。

先准备两条完整执行:A 改用 Decimal 并通过测试,B 保留浮点输出。标注者选择 A,标签就是“A 优于 B”。训练奖励模型(RM)时,将“任务+执行 A”和“任务+执行 B”分别输入同一个模型,得到分数 rA 与 rB。

A · 奖励模型怎样学会评分
任务 + 完整执行 ADecimal 求和 → 输出 0.30
任务 + 完整执行 Bfloat 求和 → 保留误差
同一个 RM语言模型 + 标量头
两次前向计算rA, rB
偏好标签:A 优于 B
偏好损失−log σ(rA − rB)
反向传播 · 更新 RM 参数
图 2 · 两条完整执行分别经过同一个 RM。偏好标签监督分数的相对顺序,损失反向传播到 RM。训练完成后,RM 在 PPO 中固定。
LRM=−log⁡σ(rA−rB)

σ 是 sigmoid 函数,把分差转换成偏好概率。最小化这个损失,会鼓励 A 的相对分数更高;大量偏好对让 RM 学会评价新执行。人工提供偏好顺序,RM 学习相应的分值。RM 通常使用语言模型骨干接一个标量输出头,输出单个分数。[1]

3 B · 让 Actor 完成一次尝试

输入采用 JSONL,即每行一个 JSON 对象。原脚本把金额转成 float 后求和,得到 0.30000000000000004。Actor 要找到这个问题,改用 Decimal 处理金额字符串,再将结果格式化为两位小数。

这里采用基于人类反馈的强化学习(RLHF)中的四角色设置。Rollout 是让当前 Actor 在环境中完成一次尝试。它逐个生成 token,即文字的编码单位,组成工具调用和最终答复;环境返回文件内容与测试日志,成为下一次生成的上下文。

B · Actor 与工具如何完成一次修复
任务:把 "0.10" 与 "0.20" 相加,输出 0.30
Actor
工具环境
读取脚本cat summarize.py
读取到 float 求和代码float(row["amount"])
运行测试pytest -q
测试失败0.30000000000000004
写入修复Decimal(row["amount"])
文件已更新format(total, ".2f")
再次测试pytest -q
测试通过0.30
提交修复与测试结果
RM 读取完整执行,给分 R = 8
图 3 · 金额汇总教学案例。工具返回加入历史,Actor 据此生成下一步调用。执行完成后,整条记录交给 RM 评分。

Actor 负责生成;RM 在执行结束后读取任务与完整记录,给出最终分数;Critic 在各生成位置读取当时的前缀,预测后续回报;固定的参考模型 Reference 对相同上下文与已生成 token 计算概率,用来衡量策略偏离起点的程度。

图中“测试通过”先是一条工具观察,最终奖励由 RM 给出。若有可靠的自动验收程序,也可以直接用验收结果构造奖励,替代 RM。

训练的掩码标出 Actor 生成的位置。文件内容和测试日志保留在输入中,帮助模型判断;策略损失只作用于它生成的 token。Critic 的前缀预测可在轨迹收集后批量计算,输入仍截止于对应时刻。

4 C · Critic 怎样从结果中学习

价值网络 Critic 预测当前 Actor 从某段上下文继续执行后的平均回报。假设同题四种结果等概率,固定 RM 给出 2、4、6、8 分,平均值便是 5。Critic 从一次次结果中学习这个均值;这里的数值采用示意刻度。

回报是从某个位置往后累积的奖励。训练 Critic 时,先执行到结果已知,再把前面的历史片段与各自回报目标配成样本。广义优势估计(GAE)负责用奖励和价值预测计算这些目标,下面先看它的数据流。

C · 从完整结果构造 Critic 的训练样本
完整修复轨迹 τ
RM固定参数
R = 8
两个位置的前缀h₁:修复前 h₂:修复后
Critic预测后续回报
本次预测V(h₁) = 5
V(h₂) = 7
GAE · 构造目标Ĝt = At + Vt
回报目标 ĜtĜ₁ = 8 · Ĝ₂ = 8
价值回归损失mean (Vφ(ht) − Ĝt)²
反向传播 · 更新 Critic
At 供 Actor 更新
A₁ = 3 · A₂ = 1
图 4 · 同一条执行产生多条“历史前缀—回报目标”样本。只在终点给 R=8,β=0、γ=λ=1,故两处目标均为 8,优势分别为 3 与 1。本次回归使用固定目标。

Critic 也常用语言模型骨干加标量头实现。InstructGPT 用 RM 参数初始化价值网络,再用轨迹回报继续训练;复用的是起始参数,后续监督来自各段前缀的回报目标。[1]

Critic 将每段前缀与回报目标配成样本。若预测 5、目标 8,平方误差是 9;对误差反向传播,由优化器调整可训练参数。完整微调时,骨干与标量头都参与更新。目标在这次更新中固定,RM 不随这项损失更新。

LV = mean [Vφ(ht) − Ĝt]2

φ 是 Critic 的参数。不同结果反复出现,回归逐渐学到平均回报。它提供随上下文变化的基线,减少采样带来的梯度波动。直接使用回报也能训练策略;合适的价值预测让有限样本的更新更稳定。[3]

RM 用偏好关系学习评分标准,Critic 用实际回报学习预期。PPO 阶段通常固定 RM、继续训练 Critic。Actor 更常生成高分执行时,即使评分标准不变,Critic 的预测也应随之提高。

常见 RLHF-PPO 将最终 RM 分数与参考约束组合。对生成位置 t,一个常用的采样形式是:

rt = −β [log πold(at | ht) − log πref(at | ht)] + 𝟙t=T R

ht 是前缀,at 是生成 token,T 是最后一个生成位置。R 只在终点加入;β 控制参考约束强度。对动作分布求期望时,前面的对数概率差对应 KL 散度。[1]

广义优势估计(GAE)结合奖励与价值预测,从后往前计算每个生成位置的优势:

δt = rt + γ(1 − dt)Vt+1 − Vt
At = δt + γλ(1 − dt)At+1
Ĝt = At + Vt

δ 是一步预测差,γ 折扣后续奖励,λ 控制后续优势的保留程度;d=1 表示任务真正结束。Ĝ 是给 Critic 的回报目标。这里 t 枚举生成决策,工具返回进入下一位置的上下文。[2]

取示例最终分数 R=8,暂令 β=0、γ=λ=1,整条轨迹仅在真正结束时奖励。此时起点预测 V=5,优势是 +3;修复后另一个位置预测 V=7,优势是 +1。两处回报目标都是 8,但与各自预期的差值不同。

5 D · Actor 怎样更新概率

Actor 使用优势调整已采样行为的概率。生成这一批轨迹的策略称为 πold,正在更新的策略是 πθ:

D · Actor 如何用同一批轨迹学习
固定的一批轨迹前缀 ht · 已采样 token at
正在训练的 Actorπθ
重新计算概率πθ(at | ht)
采样时保存的概率πold(at | ht)
新旧概率比 ρtπθ / πold
优势 AtGAE → At
PPO 裁剪损失
反向传播 · 更新 Actor 参数 θ
图 5 · 重算已采样 token 的概率,与采样时保存的旧概率比较。优势给出更新方向,裁剪目标抑制过大的改动。新 Actor 再收集下一批轨迹。
ρt = πθ(at | ht) / πold(at | ht)
Lπ = −mean min [ρtAt, clip(ρt, 1 − ε, 1 + ε)At]

正优势鼓励提高相应概率,负优势给出相反方向。clip 将概率比截到指定区间,限制目标中继续放大更新的收益;实际更新还受整批样本影响。[4]

旧策略与参考模型承担不同工作。旧策略给本批更新提供比较起点,换批后随之更新;参考模型通常长期固定在 SFT 起点。旧概率可随轨迹保存,不必为它再常驻第五个模型。

6 长轨迹怎样影响学习

一次成功会同时包含排错、有效修改和多余操作。终点得分经过优势估计传回各位置,反馈仍有噪声;Critic 的预测偏差也会进入这些优势。Actor 持续变化,因此价值网络需要持续跟进。

工具日志还会改变轨迹长度。实现需要明确哪些位置参与优势递推、每隔多长应用一次折扣;仅屏蔽日志的策略损失,并没有确定递推规则。计算时分块,应续接后继价值与优势;真正终止与中途截断需要分别处理。

评分也要跟上目标。若 RM 偏爱漂亮的完成声明,模型可能高分而未修好程序;测试、偏好数据和留出评估要覆盖实际交付。另一方面,更新过猛会让旧轨迹迅速过时,过强的 KL 约束又会抑制探索。学习率、裁剪、评分质量与采样成本需要一起考虑。[5]

7 GRPO 与 DPO 改变了什么

GRPO 对同一道题生成一组答案,用组内均值和标准差计算相对优势,省去 Critic。原始方法仍使用 RM 和参考模型;改用自动验收奖励还可省去 RM。同题多次执行增加采样成本,全组同分时则没有相对奖励差异。[6]

标准离线 DPO 直接使用“A 优于 B”的已有数据,保留 Actor 与参考模型,省去独立 RM、Critic 和在线采样评分循环。它将带 KL 正则的奖励优化改写为策略概率目标:奖励可由策略与参考的对数概率比表示,同题共有的归一化项在比较两份答案时相消。偏好数据的质量与覆盖由此成为关键。[7]

在代码任务中,选择还取决于一次执行有多贵、能否可靠验收,以及有没有成对偏好数据。Terminal-RSI 采用验证器奖励与 PPO,并研究长轨迹的优势估计和 Critic 交接;它没有独立的偏好 RM。

1 学習ループの全体像

コード Agent はファイルを読み、ツールを呼び出し、コードを修正する。行動とツールの返り値を合わせた記録を軌跡と呼ぶ。PPO は実行結果を使い、途中で生成した行動の確率を調整する。

報酬モデルを用いる人間のフィードバックによる強化学習(RLHF)では、Actor が行動を生成し、RM が完了した実行を評価し、Critic が現在の文脈から先のリターンを予測し、Reference が固定した方策の参照を与える。報酬と価値予測からアドバンテージを計算し、Actor と Critic の学習目標を作る。図の A—D が以下の四つの節に対応する。

学習の全体像
A · PPO の前
操作の実演教師あり学習 SFTActor + Reference同じ初期方策の二つのコピー選好ペアRM を学習
B · タスクを実行
C · 報酬とアドバンテージ
D · パラメータを更新
Actor現在の方策 πoldツール環境ファイル・Shell・テスト軌跡の記録タスク+行動+観測RM重みを固定Reference重みを固定Critic各時点までの履歴を読む報酬 rt を作る終点スコア+KL 制約GAE各位置へ評価を遡らせるActor を更新PPO のクリップ目的関数Critic を更新リターン目標 Ĝt に回帰
ツール呼び出し
ツールの返り値
完了した実行
接頭辞+token
接頭辞 ht
スコア R
参照確率
rt
価値 Vt
アドバンテージ At
リターン目標 Ĝt
採用済み token と旧確率
更新した Actor で次のバッチを収集
更新後の価値予測
保存した log πold
図 1 · A はモデル準備、B は軌跡収集、C は報酬とアドバンテージ計算、D は Actor と Critic の更新。PPO 中の RM と Reference は固定。各ノードから対応する節へ移動できる。

2 A · 方策と報酬モデルを準備する

学習は通常、既存の言語モデルに対する教師ありファインチューニング(SFT)から始まる。適切な操作の実演を与え、その文脈で同じ操作を生成する確率を高める。その後、PPO では方策ネットワークである Actor が自ら試行し、新しい結果から学ぶ。[1]

SFT 後の方策を二つにコピーする。一方を学習し続ける Actor、もう一方を固定した Reference とする。Reference は生成済み token の確率を計算し、Actor が初期方策から離れる度合いを制約する。

金額集計スクリプトの修正を例にする。文字列の金額 "0.10" と "0.20" を正確に加算し、0.30 を出力する。軌跡と点数は説明用に構成した例である。

まず 2 つの完全な実行を用意する。A は Decimal に修正してテストに合格し、B は浮動小数点の出力を残している。評価者が A を選ぶと、ラベルは「A のほうが B より望ましい」となる。報酬モデル(RM)の学習では、「課題+実行 A」と「課題+実行 B」を同じモデルに別々に入力し、スコア rA と rBを得る。

A · 報酬モデルはどう学ぶか
課題+完了済み実行 ADecimal で加算 → 0.30
課題+完了済み実行 Bfloat で加算 → 誤差が残る
同一の RM言語モデル+スカラーヘッド
二回の順伝播rA, rB
選好ラベル:A が B より良い
選好損失−log σ(rA − rB)
逆伝播で RM の重みを更新
図 2 · 二つの完了済み実行を同一の RM で採点する。選好ラベルでスコアの順序を学び、損失を RM に逆伝播する。学習後は PPO 中に固定する。
LRM=−log⁡σ(rA−rB)

σ はシグモイド関数で、スコア差を選好の確率に変換する。この損失を小さくすると、A の相対的なスコアが高くなる方向に学習が進む。多数の選好ペアから、新しい実行を評価する基準を学ぶ。評価者は選好の順序を与え、RM がスコアを学ぶ。RM は一般に、言語モデルの本体に単一の数値を出すスカラー出力ヘッドを加えて構成する。[1]

3 B · Actor に一回の試行をさせる

入力は 1 行に 1 個の JSON オブジェクトを置く JSONL 形式である。元のスクリプトは金額を float に変換し、0.30000000000000004 を出力する。Actor は問題を見つけ、金額の文字列を Decimal で処理し、小数点以下 2 桁で表示するよう直す。

ここでは人間のフィードバックによる強化学習(RLHF)の 4 つの役割を使う。Rollout は、現在の Actor が環境の中で行う 1 回の試行である。Actor は文字列の符号化単位である token を順に生成し、ツール呼び出しや最終回答を作る。環境から返るファイル内容やテストログは、次の生成の文脈に加わる。

B · Actor とツールによる一回の修正
課題:"0.10" と "0.20" を加算し、0.30 を出力
Actor
ツール環境
スクリプトを読むcat summarize.py
float による加算を確認float(row["amount"])
テストを実行pytest -q
テスト失敗0.30000000000000004
修正を適用Decimal(row["amount"])
ファイルを更新format(total, ".2f")
再テストpytest -q
テスト成功0.30
修正とテスト結果を提出
RM が完了した実行を評価:R = 8
図 3 · 金額集計を修正する学習用の例。ツールの返り値を履歴に加え、次の呼び出しを生成する。実行完了後に全記録を RM で採点する。

Actor は行動を生成する。RM は実行終了後に課題と全記録を読み、最終スコアを出す。Critic は各生成位置でその時点までの接頭辞を読み、先のリターンを予測する。固定した参照モデル Reference は、同じ文脈で生成された token の確率を計算し、方策が出発点からどれだけ変化したかを測る基準となる。

この例の「テスト合格」はツールからの観測で、最終報酬は RM が与える。信頼できる自動検証器があれば、その判定から直接報酬を作り、RM を置き換えることもできる。

学習のマスクは、Actor が生成した位置を指定する。ファイル内容とテストログは判断材料として入力に残し、方策の損失は生成した token にだけ適用する。Critic の予測は軌跡収集後にまとめて計算できるが、各予測が参照する入力は対応する時点までに限られる。

4 C · Critic は結果からどう学ぶか

価値ネットワーク Critic は、現在の Actor がある文脈から実行を続けた場合の平均リターンを予測する。同じ課題で 4 種類の結果が等確率で生じ、固定した RM が 2、4、6、8 点を付けるとすれば、平均は 5 になる。Critic は繰り返し得られる結果から、この期待値を学ぶ。この点数は説明用の尺度である。

リターンは、ある位置から先の報酬を累積した値である。Critic の学習では、試行を終えてから過去の履歴の接頭辞と対応するリターン目標を組にする。一般化アドバンテージ推定(GAE)が報酬と価値予測から目標を作る。そのデータの流れを次の図に示す。

C · 実行結果から Critic の学習例を作る
完了した修正の軌跡 τ
RM重みを固定
R = 8
二つの位置の接頭辞h₁:修正前 h₂:修正後
Critic今後のリターンを予測
現在の予測V(h₁) = 5
V(h₂) = 7
GAE・目標を作るĜt = At + Vt
リターン目標 ĜtĜ₁ = 8 · Ĝ₂ = 8
価値の回帰損失mean (Vφ(ht) − Ĝt)²
逆伝播で Critic を更新
At は Actor の更新へ
A₁ = 3 · A₂ = 1
図 4 · 一回の実行から複数の「接頭辞—リターン目標」を作る。終点のみ R=8、β=0、γ=λ=1 では両目標は 8、アドバンテージは 3 と 1。この回帰中は目標を固定する。

Critic も一般に、言語モデルの本体とスカラー出力ヘッドで構成する。InstructGPT は RM のパラメータで価値ネットワークを初期化し、その後は軌跡のリターンで学習した。再利用するのは初期パラメータであり、その後の教師信号は各接頭辞に対応するリターン目標となる。[1]

Critic の学習サンプルは、接頭辞とリターン目標のペアである。予測が 5、目標が 8 なら、二乗誤差は 9 になる。この誤差を逆伝播し、オプティマイザで学習可能なパラメータを調整する。全パラメータの微調整では、言語モデルの本体とスカラー出力ヘッドの両方を更新する。今回の更新中は目標を固定し、この損失で RM を更新することはない。

LV = mean [Vφ(ht) − Ĝt]2

φ は Critic のパラメータを表す。さまざまな結果を繰り返し観測すると、回帰によって平均リターンを学ぶ。文脈に応じたベースラインは、サンプリングによる方策勾配の揺らぎを減らす助けになる。リターンを直接使って方策を学習することもできるが、適切な価値予測は限られたサンプルでの更新を安定させる。[3]

RM は選好から採点基準を学び、Critic は実際のリターンから期待値を学ぶ。PPO の段階では通常 RM を固定し、Critic の学習を続ける。Actor が高得点の実行を生む頻度が上がれば、採点基準が同じでも Critic の予測は上がる。

一般的な RLHF-PPO では、最終的な RM スコアと参照モデルからの乖離に対するペナルティを組み合わせる。生成位置 t でよく使われるサンプルベースの形は次の通りである。

rt = −β [log πold(at | ht) − log πref(at | ht)] + 𝟙t=T R

ht は接頭辞、at は生成 token、T は最後の生成位置である。R は終点でだけ加え、β が参照制約の強さを決める。行動分布について期待値を取ると、この対数確率差は KL ダイバージェンスに対応する。[1]

一般化アドバンテージ推定(GAE)は、報酬と価値予測を組み合わせ、後ろから各生成位置のアドバンテージを計算する。

δt = rt + γ(1 − dt)Vt+1 − Vt
At = δt + γλ(1 − dt)At+1
Ĝt = At + Vt

δ は 1 ステップの予測誤差、γ は将来の報酬の割引率、λ は後続のアドバンテージをどれだけ残すかを決める。d=1 は課題が実際に終了したことを表す。Ĝ は Critic に与えるリターン目標である。ここで t は生成の意思決定を数え、ツールの観測は次の位置の文脈に入る。[2]

例の最終スコアを R=8 とし、β=0、γ=λ=1、報酬は実際の終了時にだけ与える。このとき、出発点の予測が V=5 ならアドバンテージは +3、修正後の別の位置で V=7 なら +1 となる。リターン目標はどちらも 8 だが、その時点での予測との差が異なる。

5 D · Actor は確率をどう更新するか

Actor はアドバンテージに応じて、サンプルされた行動の確率を調整する。このバッチを収集した方策を πold、更新中の方策を πθ とする。

D · Actor は同じバッチからどう学ぶか
固定した一つのバッチ接頭辞 ht・採用済み token at
更新中の Actorπθ
確率を再計算πθ(at | ht)
収集時に保存した確率πold(at | ht)
新旧確率比 ρtπθ / πold
アドバンテージ AtGAE → At
PPO クリップ損失
逆伝播で Actor の重み θ を更新
図 5 · 採用済み token の確率を再計算し、保存した旧確率と比較する。アドバンテージが更新方向を与え、クリップで大きな変化への誘因を抑える。更新後の Actor で次のバッチを収集する。
ρt = πθ(at | ht) / πold(at | ht)
Lπ = −mean min [ρtAt, clip(ρt, 1 − ε, 1 + ε)At]

正のアドバンテージは対応する確率を高める方向、負なら逆方向に働く。clip は目的関数内の確率比を指定範囲に制限し、更新をさらに大きくする誘因を抑える。実際のパラメータ更新にはバッチ全体のサンプルも影響する。[4]

旧方策と参照モデルは役割が異なる。旧方策は今回のバッチの更新基準であり、後のバッチでは入れ替わる。参照モデルは通常、SFT の出発点に固定する。旧方策の対数確率は軌跡と一緒に保存できるため、5 つ目のモデルを常駐させる必要はない。

6 長い軌跡が学習を難しくする理由

成功した実行にも、調査、有効な修正、不要な操作が混在する。終点の評価はアドバンテージ推定を通じて途中の位置に伝わるが、依然としてノイズを含む。Critic の予測誤差もその推定に入る。Actor が変化し続けるため、Critic も追従する必要がある。

ツールログは軌跡の長さにも影響する。実装では、どの位置をアドバンテージの再帰計算に含め、どの間隔で割引を適用するかを明示する必要がある。ログを方策損失から除外するだけでは、この規則は決まらない。計算を分割する場合は後続の価値とアドバンテージを境界越しに引き継ぎ、実際の終了と途中の打ち切りを区別する。

採点基準も目的に合わせる必要がある。RM が整った完了報告を好むと、実際にはプログラムが直っていなくても高得点になり得る。テスト、選好データ、学習に使わない評価で成果物そのものを確かめる。一方、大きすぎる更新は収集済みの軌跡を早く陳腐化させ、強すぎる KL 制約は探索を抑える。学習率、クリップ、採点の質、サンプリングコストを合わせて考える必要がある。[5]

7 GRPO と DPO は何を変えるか

GRPO は同じ課題に対して回答群を生成し、群内の平均と標準偏差から相対的なアドバンテージを計算して Critic を省く。原著の手法は RM と参照モデルを残し、自動検証による報酬を使えば RM も置き換えられる。同じ課題を複数回実行するためサンプリングコストが増え、全回答が同点なら相対的な報酬差は得られない。[6]

標準的なオフライン DPO は、既存の「A のほうが B より望ましい」というデータで直接学習する。Actor と参照モデルを残し、独立した RM、Critic、オンラインの生成・採点ループを省く。KL 正則化付きの報酬最適化を、方策確率の目的関数として書き換える。報酬は方策と参照モデルの対数確率比で表現でき、同じ課題に対する 2 つの回答を比較すると共通の正規化項が消える。そのため、選好データの質とカバー範囲が重要になる。[7]

コード課題での選択は、1 回の実行コスト、検証の信頼性、選好ペアの有無にもよる。Terminal-RSI は検証器の報酬と PPO を使い、長い軌跡でのアドバンテージ推定と Critic の引き継ぎを研究する。独立した選好 RM は使用しない。

Terminal-RSI: From Execution to Recursive TrainingTerminal-RSI:从终端执行到递归训练Terminal-RSI:実行経験から再帰的な学習へ →

Figures and code图与代码図とコード

Download article and figure sources (JSON)下载正文与可编辑图源(JSON)本文と編集可能な図のソースをダウンロード(JSON)