TRPO:先找更新方向,再检查分布变化
Trust region policy optimization
计算Fisher方向并回溯,区分真实KL检查、局部二阶近似与逐状态理论界。
trpo参数只动一点,动作概率会动多少?
同样给logit加0.5,原本概率0.5的动作与原本概率0.99的动作,分布变化并不相同。TRPO用策略分布的变化约束更新,而不只看参数欧氏距离。它先求一个局部候选方向,再用真实KL和代理目标检查候选步是否可接受。TRPO原文
本篇的教学环境有三个上下文,每次只选一个二元动作就结束。上下文权重为[0.3,0.4,0.3];第一种上下文奖励动作0,其余两种奖励动作1,正确动作得1。策略用两个共享参数和特征[1,−1]、[1,0.25]、[1,1]。这个小例保留分布约束、Fisher求解和回溯,但省去了长轨迹的访问分布变化。
局部代理、曲率模型与最终检查
令theta0是收集数据的旧策略参数,A0是按旧策略估计并冻结的优势。新旧概率比把旧策略下的动作样本重新加权;假设旧策略在被用到的动作上概率非零。省略与theta无关常数,代理为:
mu0是旧策略下选定的状态权重;若采用归一化折扣访问分布,完整目标中相应的正常数需一致处理。在一般多步任务里,代理保持旧状态分布,不能直接等同新策略真实回报。两者在合适条件下局部一阶一致,但离旧策略越远,差别可能越大。代理推导
本篇固定KL方向为old||new。对平均状态约束,定义KL及旧参数处的Hessian F:
旧点处KL为零、梯度为零;其局部二阶模型是Fisher曲率。令g为旧点处代理梯度,Delta为参数增量;若F正定且g非零,线性目标和二次约束的拉格朗日条件给出:
这解释了自然梯度方向和步长缩放,但二次近似不是实际KL。F可能奇异;程序用F加0.01I阻尼求方向和尺度,再用未加阻尼的真实KL检查。阻尼改变了局部度量,不能把所得步冒充精确未阻尼约束解。局部求解与实现
不必构建大型稠密F。对Bernoulli共享特征策略,F乘向量可直接求和;共轭梯度反复调用这个乘法去解线性系统:
共轭梯度从x=0、残差r=g、方向p=r开始,每轮用alpha=(r·r)/(p·Hp)沿p更新x和r,再用新旧残差平方比形成下个共轭方向。小到阈值的残差直接停止;非正曲率不能继续除。H是阻尼后的算子。一般实现的Hessian向量积也可由自动微分获得,成本不同于显式求逆。
最后按系数1、1/2、1/4……缩小候选步,从同一个旧参数起点试探。程序要求两个条件同时成立;有限次尝试均失败时保留原参数:
论文的理论界涉及逐状态最大变化和精确优势;实践常用采样平均KL、近似优势及局部模型。它们不是同一保证。两个状态中,普通状态不变,权重0.001的稀有状态从二元概率0.5变为0.99:
平均合格仍允许稀有状态变化很大。对真实RL,代理误差、有限数据和分布变化进一步影响回报,不能把小平均KL说成每个状态或每次更新的性能保证。
两维求解也保留回溯与失败恢复
标准库程序精确枚举三个上下文和两个动作,用old||new KL、阻尼0.01、KL上限0.01、最多12次折半回溯,进行12次更新。这里优势和分布可以精确计算,因此不是基于轨迹采样的完整TRPO训练器。旧概率和优势在每轮求解及回溯中固定。
"""Small exact-distribution TRPO update for a shared-feature contextual bandit.
No trajectory importance correction, neural network, or benchmark claim.
The candidate is accepted only after measuring old||new KL and surrogate gain.
"""
import json
import math
FEATURES = ((1., -1.), (1., 0.25), (1., 1.))
WEIGHTS = (0.3, 0.4, 0.3)
REWARDS = ((1., 0.), (0., 1.), (0., 1.))
def dot(a, b):
if len(a) != len(b):
raise ValueError('vector dimensions differ')
return sum(x*y for x, y in zip(a, b))
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 old_new_kl(old_logit, new_logit):
# KL(Bernoulli(sigmoid(old)) || Bernoulli(sigmoid(new))).
p = sigmoid(old_logit)
sigmoid(new_logit) # Validate finite input.
return softplus(new_logit)-softplus(old_logit)-p*(new_logit-old_logit)
def batch(theta):
rows = []
for x, w, (r0, r1) in zip(FEATURES, WEIGHTS, REWARDS):
old_logit = dot(theta, x)
p = sigmoid(old_logit)
value = (1-p)*r0+p*r1
rows.append((x, w, old_logit, r0-value, r1-value))
return tuple(rows)
def surrogate(theta, rows):
return sum(w*((1-sigmoid(dot(theta, x)))*a0+sigmoid(dot(theta, x))*a1)
for x, w, _, a0, a1 in rows)
def mean_kl(theta, rows):
return sum(w*old_new_kl(old, dot(theta, x)) for x, w, old, _, _ in rows)
def gradient(rows):
n = len(rows[0][0])
return [sum(w*sigmoid(old)*(1-sigmoid(old))*(a1-a0)*x[j]
for x, w, old, a0, a1 in rows) for j in range(n)]
def fisher_product(vector, rows, damping=0.01):
if not math.isfinite(damping) or damping < 0:
raise ValueError('nonnegative finite damping required')
result = [damping*v for v in vector]
for x, w, old, _, _ in rows:
p = sigmoid(old)
scale = w*p*(1-p)*dot(x, vector)
result = [r+scale*xi for r, xi in zip(result, x)]
return result
def conjugate_gradient(product, b, max_iter=20, tolerance=1e-12):
if max_iter < 1 or not math.isfinite(tolerance) or tolerance <= 0:
raise ValueError('positive iteration count and tolerance required')
if not b or not all(math.isfinite(x) for x in b):
raise ValueError('nonempty finite right hand side required')
x, r, p = [0.]*len(b), list(b), list(b)
rr = dot(r, r)
if rr <= tolerance**2:
return x
for _ in range(max_iter):
hp = product(p)
curvature = dot(p, hp)
if not math.isfinite(curvature) or curvature <= 0:
raise ValueError('nonpositive or nonfinite search curvature')
alpha = rr/curvature
x = [xi+alpha*pi for xi, pi in zip(x, p)]
r = [ri-alpha*hi for ri, hi in zip(r, hp)]
new_rr = dot(r, r)
if new_rr <= tolerance**2:
return x
p = [ri+new_rr/rr*pi for ri, pi in zip(r, p)]
rr = new_rr
return x
def trust_step(theta, rows, limit=0.01, damping=0.01, backtracks=12):
if not math.isfinite(limit) or limit <= 0 or backtracks < 0:
raise ValueError('positive finite KL limit and nonnegative backtracks required')
if not rows or any(len(x) != len(theta) or abs(old-dot(theta, x)) > 1e-12
for x, _, old, _, _ in rows):
raise ValueError('rows must describe this old policy')
g = gradient(rows)
if dot(g, g) < 1e-24:
return list(theta), {'accepted': False, 'reason': 'zero_gradient', 'kl': 0., 'gain': 0.}
product = lambda v: fisher_product(v, rows, damping)
direction = conjugate_gradient(product, g)
quadratic = dot(direction, product(direction))
if not math.isfinite(quadratic) or quadratic <= 0:
raise ValueError('invalid quadratic model')
scale = math.sqrt(2*limit/quadratic)
old_objective = surrogate(theta, rows)
for index in range(backtracks):
fraction = 0.5**index
candidate = [old+fraction*scale*d for old, d in zip(theta, direction)]
kl = mean_kl(candidate, rows)
gain = surrogate(candidate, rows)-old_objective
if math.isfinite(kl) and math.isfinite(gain) and kl <= limit and gain > 0:
return candidate, {'accepted': True, 'fraction': fraction, 'kl': kl, 'gain': gain}
return list(theta), {'accepted': False, 'reason': 'line_search_failed', 'kl': 0., 'gain': 0.}
def expected_return(theta):
return sum(w*((1-sigmoid(dot(theta, x)))*r0+sigmoid(dot(theta, x))*r1)
for x, w, (r0, r1) in zip(FEATURES, WEIGHTS, REWARDS))
def main():
theta, history = [0., 0.], []
for _ in range(12):
theta, info = trust_step(theta, batch(theta))
history.append(dict(info, value=expected_return(theta), logits=list(theta)))
rare = old_new_kl(0., math.log(99.))
print(json.dumps({'initial_return': 0.5, 'history': history,
'rare_state': {'mean_kl': 0.001*rare, 'max_kl': rare},
'direction': {'old_0_8_new_0_5': old_new_kl(math.log(4.), 0.),
'old_0_5_new_0_8': old_new_kl(0., math.log(4.))}}, indent=2))
if __name__ == '__main__':
main()
查看完整运行结果
{
"initial_return": 0.5,
"history": [
{
"accepted": true,
"fraction": 1.0,
"kl": 0.009416551979636756,
"gain": 0.06357512998936987,
"value": 0.5635751299893699,
"logits": [
0.0897309489111102,
0.31497394311654997
]
},
{
"accepted": true,
"fraction": 1.0,
"kl": 0.009219273247272864,
"gain": 0.06145530770845891,
"value": 0.6250304376978288,
"logits": [
0.18131799820683048,
0.634103061644611
]
},
{
"accepted": true,
"fraction": 1.0,
"kl": 0.00900276956590894,
"gain": 0.0583255112185675,
"value": 0.6833559489163963,
"logits": [
0.27855411072156344,
0.965757570193035
]
},
{
"accepted": true,
"fraction": 1.0,
"kl": 0.008763287566087597,
"gain": 0.05442405023281381,
"value": 0.7377799991492101,
"logits": [
0.38558991227888373,
1.3188198189763938
]
},
{
"accepted": true,
"fraction": 1.0,
"kl": 0.00849391901596096,
"gain": 0.04998595820603277,
"value": 0.7877659573552429,
"logits": [
0.5071768791490894,
1.7031622142383194
]
},
{
"accepted": true,
"fraction": 1.0,
"kl": 0.008183323166937543,
"gain": 0.0451834819208034,
"value": 0.8329494392760463,
"logits": [
0.6487656235970767,
2.1299546555336564
]
},
{
"accepted": true,
"fraction": 1.0,
"kl": 0.007812439362546563,
"gain": 0.0400767747323511,
"value": 0.8730262140083973,
"logits": [
0.8164074787312559,
2.6116986930219124
]
},
{
"accepted": true,
"fraction": 1.0,
"kl": 0.00735002057989406,
"gain": 0.03462050897657821,
"value": 0.9076467229849756,
"logits": [
1.0165397927384996,
3.1619776128621377
]
},
{
"accepted": true,
"fraction": 1.0,
"kl": 0.006751411970818527,
"gain": 0.028766566304586606,
"value": 0.9364132892895621,
"logits": [
1.255917237306447,
3.795127254585874
]
},
{
"accepted": true,
"fraction": 1.0,
"kl": 0.005967045755024265,
"gain": 0.022620640947955545,
"value": 0.9590339302375177,
"logits": [
1.5417239782041754,
4.525923413961706
]
},
{
"accepted": true,
"fraction": 1.0,
"kl": 0.0049654229394753766,
"gain": 0.01652839716616252,
"value": 0.9755623274036802,
"logits": [
1.8807525493874544,
5.368482148711809
]
},
{
"accepted": true,
"fraction": 1.0,
"kl": 0.003776325765472546,
"gain": 0.01101676367970683,
"value": 0.986579091083387,
"logits": [
2.274839517758609,
6.33283422145156
]
}
],
"rare_state": {
"mean_kl": 0.0016144630803608506,
"max_kl": 1.6144630803608506
},
"direction": {
"old_0_8_new_0_5": 0.19274475702175742,
"old_0_5_new_0_8": 0.2231435513142097
}
}回报从0.5提高到约0.986579,12步均通过实际KL和代理改善检查;最后一轮KL约0.003776。单步上下文任务的访问权重不变,所以本例代理改善恰好等于真实回报改善。这项等式不能直接移植到状态访问会变化的长任务。
N个上下文、d维参数的一次Fisher乘法用O(Nd)时间和O(d)工作空间;K轮共轭梯度约O(KNd),J次回溯再需O(JNd)。显式稠密F存储为O(d平方),本程序没有构建它。已测试零梯度、零残差、非正曲率及回溯失败保留参数。
方向和距离都要写清楚
KL不对称。old||new与new||old在旧点共享局部Fisher,并不意味着远处数值或回溯决策相同。所参考Spinning Up固定版本文档写new||old,TF1分类实现用old||new,Gaussian实现用new||old;教学统一为论文方向,并用非对称例检查。文档与实现
稀有状态覆盖不足、优势估计误差、Fisher近奇异以及样本外分布变化,都可能削弱约束的实际作用。更严格的回溯会增加计算,也可能经常拒绝更新。PPO改用便于一阶优化的代理目标,但其剪切也不提供相同的硬KL约束。
用接受条件审查候选步
- 候选KL合格但代理目标下降,程序接受吗?答案:不接受;它必须同时满足实际KL不超限和代理严格改善。全部尝试失败则返回旧参数。
- 解矩阵[[4,1],[1,3]]乘x=[1,2],x是什么?答案:[1/11,7/11]。代回两行分别得1和2,可用于独立检查共轭梯度,不能仅让求解器自报收敛。
- 平均KL=0.001614为什么不能证明每个状态都低于0.01?答案:稀有状态的KL约1.614,只因其权重0.001才被平均数缩小;平均与最大值是不同约束。
- 将程序扩展到多步环境,哪项评估必须新增?答案:收集新策略的独立轨迹评估真实回报与状态覆盖,不只看旧状态分布上的代理改善。还需说明优势估计、采样误差、截断及KL方向。
区分理论界和实用算法
TRPO论文核读PDF1—6,实际查看3/4;出版社元数据确认32nd ICML2015、PMLR37:1889—1897。原文使用成本最小化,本篇统一改成回报最大化;没有核读后续结果表或另附证明。TRPO
Spinning Up固定提交038665d的TRPO文档1—134、TF1 trpo.py指定范围及core.py全161行用于核对共轭梯度、KL方向与回溯;PyTorch对应文件只是未实现的桩。没有执行或复制上游代码,本篇结果是精确上下文玩具计算。实现参考
先判断,再看解释
平均KL低于0.01,是否保证每个状态KL都低于0.01?
学习目标
- 推导KL约束的局部自然梯度步,并用矩阵向量积求解。
- 用实际old||new KL和代理改善回溯,说明平均约束的局限。
先修与延伸
查看知识关联图 →参考文献
- Trust Region Policy Optimization — scoped surrogate and practical update
John Schulman; Sergey Levine; Philipp Moritz; Michael Jordan; Pieter Abbeel · 2015 - Spinning Up — scoped TRPO documentation and TF1 implementation
OpenAI; Joshua Achiam and contributors · 2020
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(AI)
Codex · 2026-09-23 · Single AI author. Scoped reading: Publisher confirms32nd ICML2015, PMLR37:1889–1897; PDF footer mislabels31st. Read PDF1–6, viewed3/4. Cost-minimization sign, old||new KL and distinction between maximum-state bound and average constraint. No later table or separate proof audit. Read docs1–134, TF1 trpo.py1–96,165–328 and all161 core.py lines. PyTorch file is a stub. Docs/Gaussian use new||old; categorical code uses old||new. MIT reference, no upstream execution or copying. 6 paired equations and four explained exercises. Shared-feature exact contextual-bandit surrogate and old||new KL; Fisher quadratic checked by finite differences, CG against a known linear system, zero/nonpositive curvature and actual full-step rejection/half-step acceptance. Failed search restores old parameters; mean-KL rare-state counterexample retained. No trajectory benchmark or maximum-state guarantee.
- 共享特征精确上下文老虎机、old||new KL;Fisher差分、CG已知解、零/非正曲率、真实全步拒绝/半步接受和失败恢复均检查。保留平均KL稀有状态反例,不作轨迹基准或逐状态保证。
- 每题四张计算SVG,16数值/几何与36个当前响应式组合通过;十二张当前选定图均直接实看;三组保留初次捕获,三组使用实际看过的修订捕获,资产与稿件SHA绑定,完整页面验收另记。
核对的来源位置:
- Trust Region Policy Optimization — scoped surrogate and practical update · Publisher confirms32nd ICML2015, PMLR37:1889–1897; PDF footer mislabels31st. Read PDF1–6, viewed3/4. Cost-minimization sign, old||new KL and distinction between maximum-state bound and average constraint. No later table or separate proof audit.
- Spinning Up — scoped TRPO documentation and TF1 implementation · Read docs1–134, TF1 trpo.py1–96,165–328 and all161 core.py lines. PyTorch file is a stub. Docs/Gaussian use new||old; categorical code uses old||new. MIT reference, no upstream execution or copying.
相关主题