AI Wiki中文/EN

PPO:剪切代理目标,不是把策略锁在区间内

Proximal policy optimization

逐段求导剪切目标,用真实采样和大步反例检查旧概率、优势及KL早停。

本页目录直觉理解数学与方法代码实现局限与误解实验与练习研究脉络

把目标剪平,为什么概率还会跑出去?

旧策略给一个动作0.5概率。PPO-Clip设置epsilon=0.2,是否就保证下一轮概率只能落在0.4到0.6之间?不能。剪切发生在优化的代理目标中,并没有执行“把新概率投影回区间”的操作。一次足够大的梯度步就可能越过去;多个样本共享参数时,别的样本还会继续改变这个动作的概率。PPO剪切目标

PPO使用一批由旧策略采集的数据,多次优化新的策略。它保留概率比,剪平某些已经朝有益方向变化过多的样本贡献,让继续放大它们不再获得同样的局部奖励。必须按优势正负分别看,不能简单地把每个ratio替换成clip(ratio)。

正负优势在相反方向剪平;一次大步更新仍可越过剪切区间。
正负优势在相反方向剪平;一次大步更新仍可越过剪切区间。

min决定哪一侧停止奖励

对一条旧策略记录,a是已抽到的动作,s是状态。theta0及旧log概率固定,优势A也在该轮优化中固定。新旧概率比为:

rt(θ)=πθ(at∣st)πθ0(at∣st)=exp⁡(log⁡πθ(at∣st)−log⁡πθ0(at∣st)).r_t(\theta)=\frac{\pi_\theta(a_t\mid s_t)}{\pi_{\theta_0}(a_t\mid s_t)} =\exp\bigl(\log\pi_\theta(a_t\mid s_t)-\log\pi_{\theta_0}(a_t\mid s_t)\bigr).

旧概率必须在样本动作上非零。记clip把数字截到[1−epsilon,1+epsilon]。PPO-Clip最大化批次平均代理:

Lclip(θ)=1B∑t=1Bmin⁡ ⁣(rt(θ)A^t,clip⁡(rt(θ),1−ϵ,1+ϵ)A^t).L^{\mathrm{clip}}(\theta)=\frac1B\sum_{t=1}^B\min\!\left(r_t(\theta)\widehat A_t,\operatorname{clip}(r_t(\theta),1-\epsilon,1+\epsilon)\widehat A_t\right).

取min使单样本贡献不大于未剪切的rA。这个下界关系针对未剪切代理,不是任意真实回报下界。完整多步目标还要说明状态采样、折扣及优势估计约定;本篇程序选单步任务,避免把这些近似藏进循环。原文式7

设单样本贡献为ell。把优势符号带入min,得到两种分段规则:

ℓ(r,A)={Amin⁡(r,1+ϵ),A≥0,Amax⁡(r,1−ϵ),A<0.\ell(r,A)=\begin{cases}A\min(r,1+\epsilon),&A\geq0,\\A\max(r,1-\epsilon),&A<0.\end{cases}

正优势希望提高动作概率,ratio超过上界后贡献变平;若动作概率下降,负面影响仍保留。负优势希望降低动作概率,ratio低于下界后贡献变平;若反而增大概率,惩罚继续变重。因而负优势−2、ratio=1.3、epsilon=0.2时,贡献是min(−2.6,−2.4)=−2.6,并非−2.4。

在非拐点处,未变平分支按概率比求导;变平分支的该样本梯度为零:

∇θℓ={0,A>0, r>1+ϵ or A<0, r<1−ϵ,Ar∇θlog⁡πθ(a∣s),otherwise.\nabla_\theta\ell=\begin{cases} 0,& A>0,\ r>1+\epsilon\ \text{or}\ A<0,\ r<1-\epsilon,\\ Ar\nabla_\theta\log\pi_\theta(a\mid s),&\text{otherwise}. \end{cases}

在拐点本身函数不一定可微;本程序选择未剪切一侧的斜率,并用远离拐点的有限差分核对。零优势始终给零贡献。熵奖励、价值损失、共享网络等可以额外加入,但不是上面这个单独剪切项自动包含的内容。参考Spinning Up版本的策略损失没有添加熵项,虽然会记录熵。实现核对

用Bernoulli logit theta,旧theta为零,批次只有动作1且优势1。此时score为0.5;学习率10的一步产生:

θnew=0+10×0.5=5,rnew=sigmoid⁡(5)0.5≈1.986614>1.2.\theta_{\mathrm{new}}=0+10\times0.5=5,\qquad r_{\mathrm{new}}=\frac{\operatorname{sigmoid}(5)}{0.5}\approx1.986614>1.2.

梯度从旧点算出,当时尚未进入平坦区;更新不会自动在边界停下。随后即使该样本梯度变零,已经越界的参数也不会自动恢复。

KL早停是附加检查。这里能精确计算old||new KL;常见采样估计则对旧数据的log概率差取平均:

DKL(π0∥πθ)=Ea∼π0[log⁡π0(a)−log⁡πθ(a)],D^=1B∑t[log⁡π0(at)−log⁡πθ(at)].D_{\mathrm{KL}}(\pi_0\Vert\pi_\theta)=\mathbb E_{a\sim\pi_0}[\log\pi_0(a)-\log\pi_\theta(a)],\qquad \widehat D=\frac1B\sum_t[\log\pi_0(a_t)-\log\pi_\theta(a_t)].

真实KL非负,有限样本估计可能为负。若在每次梯度步前检查并在超限时停止,上一大步已经造成的超限仍在;想恢复旧参数,需要另行实现回滚或回溯,不能把早停称作硬保证。

同一批次保留同一个分母

标准库程序使用单步Bernoulli老虎机,奖励等于动作。每轮按当前策略采64条记录,保存旧log概率与优势,然后最多更新10次;共30轮,种子0—7。为单独观察策略优化,基线使用已知真实旧价值p_old,不训练评论家。它既不做优势标准化,也不加熵奖励或价值损失。

"""PPO-Clip on a sampled Bernoulli bandit with a fixed old-policy batch.

Known value p_old supplies the baseline, isolating the policy update mechanics.
Exact KL stopping is a teaching convenience; an overshoot is not rolled back.
"""
import json
import math
import random


def sigmoid(x):
    if not math.isfinite(x):
        raise ValueError('finite logit required')
    return 1/(1+math.exp(-x)) if x >= 0 else math.exp(x)/(1+math.exp(x))


def softplus(x):
    return max(x, 0.)+math.log1p(math.exp(-abs(x)))


def log_probability(theta, action):
    if action not in (0, 1):
        raise ValueError('binary action required')
    sigmoid(theta)
    return -softplus(-theta) if action else -softplus(theta)


def clipped_term(ratio, advantage, epsilon=0.2):
    if not math.isfinite(ratio) or ratio < 0 or not math.isfinite(advantage) or not 0 < epsilon < 1:
        raise ValueError('finite nonnegative ratio, finite advantage and epsilon in (0,1) required')
    clipped = max(1-epsilon, min(1+epsilon, ratio))
    return min(ratio*advantage, clipped*advantage)


def objective_gradient(theta, rows, epsilon=0.2):
    """Rows are (action, old log-probability, fixed advantage).

At the clipping kink this chooses the slope from the unclipped side.
It does not differentiate through the old policy or the advantage.
"""
    if not rows:
        raise ValueError('nonempty on-policy batch required')
    p, total, grad = sigmoid(theta), 0., 0.
    for action, old_logp, advantage in rows:
        if not math.isfinite(old_logp) or old_logp > 0:
            raise ValueError('finite nonpositive old log-probability required')
        ratio = math.exp(log_probability(theta, action)-old_logp)
        total += clipped_term(ratio, advantage, epsilon)
        flat = (advantage > 0 and ratio > 1+epsilon) or (advantage < 0 and ratio < 1-epsilon)
        if not flat:
            grad += advantage*ratio*(action-p)
    return total/len(rows), grad/len(rows)


def collect(theta, rng, size=64):
    if size < 1:
        raise ValueError('positive batch size required')
    p = sigmoid(theta)
    return tuple((action, log_probability(theta, action), action-p)
                 for action in (int(rng.random() < p) for _ in range(size)))


def old_new_kl(old, new):
    p = sigmoid(old)
    sigmoid(new)
    return softplus(new)-softplus(old)-p*(new-old)


def update(old, rows, epochs=10, lr=1., epsilon=0.2, target_kl=0.02):
    if epochs < 0 or not math.isfinite(lr) or lr <= 0 or not math.isfinite(target_kl) or target_kl <= 0:
        raise ValueError('nonnegative epochs, positive finite learning rate and KL target required')
    if any(abs(log_probability(old, a)-lp) > 1e-12 for a, lp, _ in rows):
        raise ValueError('batch old probabilities do not match the old policy')
    theta, steps = old, 0
    for _ in range(epochs):
        if old_new_kl(old, theta) > target_kl:
            break
        _, grad = objective_gradient(theta, rows, epsilon)
        theta += lr*grad
        steps += 1
    ratios = [math.exp(log_probability(theta, a)-lp) for a, lp, _ in rows]
    return theta, {'steps': steps, 'kl': old_new_kl(old, theta),
                   'min_ratio': min(ratios), 'max_ratio': max(ratios)}


def train(seed=0, cycles=30):
    if cycles < 0:
        raise ValueError('nonnegative cycles required')
    rng, theta, history = random.Random(seed), 0., []
    for _ in range(cycles):
        old = theta
        rows = collect(old, rng)
        theta, report = update(old, rows)
        history.append(report)
    return {'seed': seed, 'return': sigmoid(theta), 'logit': theta,
            'overshoot_cycles': sum(row['kl'] > 0.02 for row in history),
            'last_batch': history[-1] if history else None}


def main():
    runs = [train(seed) for seed in range(8)]
    theta, overshoot = update(0., ((1, -math.log(2.), 1.),), lr=10., epochs=10)
    print(json.dumps({'initial_return': 0.5, 'runs': runs,
                     'failures_below_0_9': [r['seed'] for r in runs if r['return'] < 0.9],
                     'one_step_overshoot': dict(overshoot, logit=theta),
                     'sign_cases': {str(a): [clipped_term(r, a) for r in (0.7, 1., 1.3)]
                                    for a in (-2., 0., 2.)}}, indent=2))


if __name__ == '__main__':
    main()
查看完整运行结果
{
  "initial_return": 0.5,
  "runs": [
    {
      "seed": 0,
      "return": 0.9964716411358783,
      "logit": 5.6433878289522355,
      "overshoot_cycles": 3,
      "last_batch": {
        "steps": 10,
        "kl": 2.7258552186271157e-11,
        "min_ratio": 1.000000439368481,
        "max_ratio": 1.000000439368481
      }
    },
    {
      "seed": 1,
      "return": 0.9956734693608243,
      "logit": 5.438653379039499,
      "overshoot_cycles": 3,
      "last_batch": {
        "steps": 10,
        "kl": 4.994611281772254e-05,
        "min_ratio": 0.8655111287152788,
        "max_ratio": 1.0006756625972426
      }
    },
    {
      "seed": 2,
      "return": 0.9936943811025546,
      "logit": 5.059988571315741,
      "overshoot_cycles": 3,
      "last_batch": {
        "steps": 10,
        "kl": 4.960305140808488e-10,
        "min_ratio": 1.0000025092051383,
        "max_ratio": 1.0000025092051383
      }
    },
    {
      "seed": 3,
      "return": 0.9957363864207287,
      "logit": 5.453365491525722,
      "overshoot_cycles": 3,
      "last_batch": {
        "steps": 10,
        "kl": 7.0194525701988e-11,
        "min_ratio": 1.0000007753450673,
        "max_ratio": 1.0000007753450673
      }
    },
    {
      "seed": 4,
      "return": 0.995073253087848,
      "logit": 5.308137440935634,
      "overshoot_cycles": 3,
      "last_batch": {
        "steps": 10,
        "kl": 1.4455078166343213e-10,
        "min_ratio": 1.0000011964550048,
        "max_ratio": 1.0000011964550048
      }
    },
    {
      "seed": 5,
      "return": 0.9932530560948812,
      "logit": 4.9918958239908475,
      "overshoot_cycles": 3,
      "last_batch": {
        "steps": 10,
        "kl": 6.955139691716856e-10,
        "min_ratio": 1.0000030741523886,
        "max_ratio": 1.0000030741523886
      }
    },
    {
      "seed": 6,
      "return": 0.996168766307803,
      "logit": 5.56072982314422,
      "overshoot_cycles": 3,
      "last_batch": {
        "steps": 10,
        "kl": 4.113652365793363e-11,
        "min_ratio": 1.000000562530886,
        "max_ratio": 1.000000562530886
      }
    },
    {
      "seed": 7,
      "return": 0.9941583395906533,
      "logit": 5.136881416234481,
      "overshoot_cycles": 3,
      "last_batch": {
        "steps": 10,
        "kl": 3.3858083909243594e-10,
        "min_ratio": 1.0000019948578016,
        "max_ratio": 1.0000019948578016
      }
    }
  ],
  "failures_below_0_9": [],
  "one_step_overshoot": {
    "steps": 1,
    "kl": 1.8135681679291729,
    "min_ratio": 1.9866142981514303,
    "max_ratio": 1.9866142981514303,
    "logit": 5.0
  },
  "sign_cases": {
    "-2.0": [
      -1.6,
      -2.0,
      -2.6
    ],
    "0.0": [
      0.0,
      0.0,
      0.0
    ],
    "2.0": [
      1.4,
      2.0,
      2.4
    ]
  }
}

正常训练的学习率为1,精确KL早停阈值0.02;检查在下一次更新前发生,无回滚。八个种子最终期望回报约0.9933—0.9965,全部高于预设0.9检查线。每个种子的超限轮数也保留在输出中。另一个学习率10的反例只更新一步即停止,仍保留theta=5、ratio约1.9866、KL约1.8136。

每次新采样才刷新旧策略,不能在每个优化epoch重算“旧”分母让ratio重新变为1。本例一个标量参数,B个样本、K次更新耗时O(KB),保存批次O(B)。多参数网络还需计入前向、反传和优化器状态;小批次、多epoch及KL估计方式都是应记录的实现选择。

剪切并未解决所有策略优化问题

剪切只改变样本代理的部分梯度,不能保证ratio、KL或真实回报界。旧数据上没有覆盖的状态动作没有相应约束;错误优势会让本来有害的动作被视为有益。共享参数又让某个样本的平坦区无法阻止其他样本移动它。

本篇单步任务的真实基线很容易取得;实际多步PPO常用价值网络及GAE,要另外处理评论家误差、片段边界和训练目标。PPO论文还提出自适应KL惩罚变体,它与这里的PPO-Clip不同。不能把所有名为PPO的实现当作同一损失和同一更新流程。两种变体

先算贡献,再判断梯度

  1. 优势2、ratio=1.3、epsilon=0.2时,贡献和局部梯度是什么?答案:贡献2.4,远离拐点时该样本梯度为零;它已经超过有益方向上限。这不限制共享参数被其他样本更新。
  2. 优势−2、ratio依次为0.7、1、1.3时,贡献是什么?答案:依次−1.6、−2、−2.6。低于下界的有益下降被剪平,增加坏动作概率的方向继续受罚。
  3. 每次epoch后把旧log概率替换为最新值,会怎样?答案:分母基准被移动,ratio不断接近1;数据却仍由原策略采集,原本对一轮数据的代理和剪切解释不再成立。
  4. 训练日志的近似KL为负,是否说明实现一定错了?答案:不能仅凭这一点断定。真实KL非负,但有限旧样本上的log差平均可以为负。检查采样分布、方向、样本量与冻结旧概率;若能精确求和,可另算真实KL对照。

版本和公式下标都值得核对

PPO初稿为2017-07-20,本篇核读2017-08-28的arXiv v2,PDF1—5,实看3/5。PDF5式10、11末奖励/残差的指数印为T−t+1;按末下标T−1展开应为T−t−1,bootstrap指数T−t保持不变。本篇GAE例已经用有限和与递推独立核对,未照抄该笔误。未核后续成绩表或复现基准。原始方法

Spinning Up固定提交038665d的PPO文档1—139、PyTorch代码1—86、224—289、302—328支持缓冲区、冻结旧概率和早停讨论。其近似KL与本篇可精确枚举的KL不同;未执行或复制上游代码。实现参考

先判断,再看解释

epsilon=0.2、优势=-2、ratio=1.3时,剪切代理贡献是多少?

选择一个答案

学习目标

  • 按优势正负计算剪切代理及梯度,区分有益和有害方向。
  • 冻结批次中的旧概率和优势,解释早停为何不能回滚先前超限。

先修与延伸

查看知识关联图 →

参考文献

  1. Proximal Policy Optimization Algorithms — arXiv v2 methods
    John Schulman; Filip Wolski; Prafulla Dhariwal; Alec Radford; Oleg Klimov · 2017
  2. Spinning Up — scoped PPO documentation and PyTorch buffer/update
    OpenAI; Joshua Achiam and contributors · 2020

版本1 · 编写状态: 已完成记录中的技术复核

查看技术检查记录(AI)

Codex · 2026-09-23 · Single AI author. Scoped reading: First2017-07-20, v2 dated2017-08-28. Read PDF1–5, viewed3/5. Clipping bounds the surrogate, not ratios. Printed last-term exponents in PDF5 Eqs10/11 corrected to T-t-1 by finite expansion; no benchmark replication. Read docs1–139; PyTorch ppo.py1–86,224–289,302–328. GAE, fixed old logp and early stopping; sample KL may be negative, stopping does not roll back, normalization lacks a zero-variance guard. MIT reference, no upstream execution or copying. 6 paired equations and four explained exercises. Both advantage-sign branches checked by finite differences away from kinks; frozen old log probabilities/advantages, sampled bandit cycles and all eight seeds retained. One large update overshoots ratio and KL despite stopping; finite-sample approximate KL can be negative. Exact known baseline and no entropy/value loss clearly scoped.

  • 远离拐点核正负优势分支有限差分,旧log概率/优势冻结,保留真实采样老虎机与八种子。大步越过ratio和KL而早停不回滚;有限样本近似KL可负。明确真实已知基线且无熵/价值损失。
  • 每题四张计算SVG,16数值/几何与36个当前响应式组合通过;十二张当前选定图均直接实看;三组保留初次捕获,三组使用实际看过的修订捕获,资产与稿件SHA绑定,完整页面验收另记。

核对的来源位置:

相关主题

没有匹配结果,试试英文名或缩写。

已显示 0 条结果

将整个查询放入双引号,可按短语匹配。