安全强化学习:平均成本达标,为什么仍会出事?
Safe reinforcement learning
用有限约束决策比较精确混合策略、经验成本与对偶更新,区分平均预算、单次风险和训练过程违约。
safe-rl平均下来没超标,和每一次都没事,是两句话
一个控制器把大多数任务做得很稳,但偶尔产生很大的损失。只看平均奖励,它可能很好;要求每条轨迹都不越界时,它却可能完全不合格。“安全”必须先落到成本、事件、概率与时间范围上,否则算法无法知道要保住什么。
安全强化学习研究带性能或风险要求的学习与决策。可以改变优化目标,如约束平均成本、重视最坏结果;也可以改变探索过程,如加入外部知识与执行限制。最终策略合格与训练过程中从未冒险,是两个分别需要证据的问题。安全目标与探索
本篇的事件是明确虚构的数值事件:发生一次记成本10,没有实际机器人或人的风险。两步任务中,最优混合策略可以做到期望成本0.5,但仍有5%概率发生事件。我们会精确算出它,并保留一个看似满足经验预算、实际却超标的学习结果。
先写清约束约束了什么
约束马尔可夫决策过程(CMDP)在奖励之外添加成本及预算。下面使用有限时域H;也可在适当折扣条件下改成无限时域。成本的单位和符号必须固定,不能把“越大越好”的奖励与“越小越好”的成本混用。CMDP定义
这些是期望约束。另两种常见要求是以某个概率不超限,以及以概率1不超限。把一条轨迹的累计成本记为Cτ,三者不能互换:
第一项不能单独确定后两项。非负成本下可以另推概率界,但需要阈值与事件定义。折扣成本还会降低远期事件的权重;如果要求永远不进入某状态,仅把远期损失折扣掉并不表达原要求。
在本例已知有限模型时,可以枚举八个确定策略,并在每回合开始随机选择一个执行到底。每个策略的期望奖励Rj和成本Cj可精确计算。单预算问题变成概率权重的线性规划:
这里的线性来自对完整回合策略做混合,不是随意平均神经网络参数。一个预算加概率和约束,使最优顶点至多需要两个正权重。于是本程序检查所有可行单策略,以及跨过预算线的策略对;没有调用隐藏优化器。若低成本策略a和高成本策略b夹住预算,b的权重为:
八个策略中有reward2/cost0与reward5/cost1这两个有效端点;预算0.5时各取一半,得到reward3.5/cost0.5。后者有0.1概率发生成本10事件,因此混合后事件概率仍为0.05。所有预算内的确定策略最多reward2,随机化在这里有实际作用。
未知大环境无法直接列全策略时,常用拉格朗日方法调节奖励与成本之间的权衡。以单约束为例,策略最大化L,而非负乘子针对超预算程度增加:对偶更新及训练期限制
固定惩罚系数不一定对应想要的预算,动态乘子也不保证每个中间策略可行。符号很重要:超预算时增加λ,从下一轮目标中扣掉更多成本。有限迭代、函数近似与采样误差仍可能留下违约。
CPO使用受约束的策略更新,在小步近似中将奖励/成本线性化,将策略距离二次化。令Δ为参数变化、g为奖励梯度、bi为成本梯度、ci为当前成本超预算量、H为局部KL曲率:
原文区分保守理论更新、信任域近似、有限样本估计、线搜索和不可行恢复;其近似约束结果也有误差项。不能把算法名当逐轨迹无事件证明。本程序不实现CPO,而用可精确求解的小问题暴露约束语义与有限步对偶行为。式10—16及实际实现
估计成本还受稀少事件影响。真实事件率p,每次独立查询,n次里一次都没遇到的概率为:
p=0.1、n=32时约3.43%,并不为零。观察计数0不能证明真实成本0,更不能证明策略安全。这个概率计算假设独立同分布查询;非平稳环境需要另作分析。
让经验可行策略接受真实成本检查
原创两步任务有三个决策状态。入口选择决定下一状态;各状态动作0奖励1、无事件,入口动作1奖励2且事件概率0.1。到第二阶段,动作1奖励4,事件概率在两条入口路线后分别为0.1和0.4。事件不改变转移,但一次增加成本10;本例使用未折扣有限回合。
程序先以已知模型计算最优混合策略作为对照,再对每个状态动作查询32次,共192次生成式查询,使用样本成本求解。奖励已知,真实成本只用于评价经验解。最后另运行200次“精确奖励减惩罚的最佳响应+投影乘子更新”,保留全部迭代。
"""Original finite CMDP: expected budgets do not imply incident-free trajectories."""
import itertools
import json
import math
import random
REWARD = ((1., 2.), (1., 4.), (1., 4.))
HAZARD = ((0., .1), (0., .1), (0., .4))
POLICIES = list(itertools.product((0, 1), repeat=3))
def policy_table(costs):
if len(costs) != 3 or any(len(row) != 2 for row in costs):
raise ValueError('Three states and two actions required')
if any(not math.isfinite(v) or v < 0 for row in costs for v in row):
raise ValueError('Finite nonnegative costs required')
result = []
for policy in POLICIES:
first = policy[0];state = 1 + first;second = policy[state]
result.append(dict(policy=policy,reward=REWARD[0][first]+REWARD[state][second],
cost=costs[0][first]+costs[state][second]))
return result
def exact_table():
return policy_table([[10*p for p in row] for row in HAZARD])
def mixture(weights, table):
if len(weights) != len(table) or any(not math.isfinite(w) or w < 0 for w in weights) or not math.isclose(sum(weights),1.):
raise ValueError('A normalized nonnegative mixture is required')
return dict(reward=sum(w*r['reward'] for w,r in zip(weights,table)),
cost=sum(w*r['cost'] for w,r in zip(weights,table)))
def solve(table, budget):
"""Enumerate vertices of one-budget simplex; no hidden optimizer."""
if not table or not math.isfinite(budget):raise ValueError('Invalid optimization problem')
candidates = []
for i,row in enumerate(table):
if row['cost'] <= budget:
w=[0.]*len(table);w[i]=1.;candidates.append(w)
for i,j in itertools.combinations(range(len(table)),2):
ci,cj=table[i]['cost'],table[j]['cost']
if min(ci,cj) < budget < max(ci,cj):
wi=(budget-cj)/(ci-cj);w=[0.]*len(table);w[i]=wi;w[j]=1-wi;candidates.append(w)
if not candidates:return None
w=max(candidates,key=lambda x:mixture(x,table)['reward'])
return dict(weights=w,**mixture(w,table))
def incident_probability(weights):
probability=0.
for w,policy in zip(weights,POLICIES):
first=policy[0];state=1+first;second=policy[state]
probability+=w*(1-(1-HAZARD[0][first])*(1-HAZARD[state][second]))
return probability
def sample_costs(seed,queries_per_pair=32):
if not isinstance(queries_per_pair,int) or queries_per_pair<1:raise ValueError('Positive query count required')
rng=random.Random(seed);counts=[]
for row in HAZARD:
counts.append([sum(rng.random()<p for _ in range(queries_per_pair)) for p in row])
return [[10*n/queries_per_pair for n in row] for row in counts],counts
def dual_learning(table,budget,iterations=200,rate=.1):
"""Exact best response plus projected multiplier; every iterate is retained."""
if iterations<1 or rate<=0:raise ValueError('Positive optimization budget required')
multiplier=0.;counts=[0]*len(table);trace=[]
for step in range(iterations):
i=max(range(len(table)),key=lambda j:table[j]['reward']-multiplier*(table[j]['cost']-budget))
row=table[i];before=multiplier;counts[i]+=1
multiplier=max(0.,multiplier+rate*(row['cost']-budget))
trace.append(dict(step=step,policy=i,reward=row['reward'],cost=row['cost'],before=before,after=multiplier))
weights=[n/iterations for n in counts]
return dict(last=table[trace[-1]['policy']],average=dict(weights=weights,**mixture(weights,table)),
violating_iterates=sum(r['cost']>budget for r in trace),trace=trace)
def experiment(seed=0):
truth=exact_table();budget=.5
costs,counts=sample_costs(seed);estimated_table=policy_table(costs)
estimated=solve(estimated_table,budget);optimal=solve(truth,budget)
evaluation=mixture(estimated['weights'],truth)
frontier=[dict(budget=b,solution=solve(truth,b)) for b in (0.,.25,.5,1.,2.,5.)]
return dict(seed=seed,budget=budget,true_table=truth,estimated_costs=costs,observed_incidents=counts,
queries_per_pair=32,generative_queries=192,optimal=optimal,
optimal_incident_probability=incident_probability(optimal['weights']),
estimated=estimated,evaluation=dict(evaluation,violation=max(0.,evaluation['cost']-budget),
incident_probability=incident_probability(estimated['weights'])),
frontier=frontier,dual=dual_learning(truth,budget))
if __name__=='__main__':
result=experiment();result['dual']={k:v for k,v in result['dual'].items() if k!='trace'}
print(json.dumps(result,indent=2))
查看运行摘要
{
"seed": 0,
"budget": 0.5,
"true_table": [
{
"policy": [
0,
0,
0
],
"reward": 2.0,
"cost": 0.0
},
{
"policy": [
0,
0,
1
],
"reward": 2.0,
"cost": 0.0
},
{
"policy": [
0,
1,
0
],
"reward": 5.0,
"cost": 1.0
},
{
"policy": [
0,
1,
1
],
"reward": 5.0,
"cost": 1.0
},
{
"policy": [
1,
0,
0
],
"reward": 3.0,
"cost": 1.0
},
{
"policy": [
1,
0,
1
],
"reward": 6.0,
"cost": 5.0
},
{
"policy": [
1,
1,
0
],
"reward": 3.0,
"cost": 1.0
},
{
"policy": [
1,
1,
1
],
"reward": 6.0,
"cost": 5.0
}
],
"estimated_costs": [
[
0.0,
0.9375
],
[
0.0,
1.5625
],
[
0.0,
5.3125
]
],
"observed_incidents": [
[
0,
3
],
[
0,
5
],
[
0,
17
]
],
"queries_per_pair": 32,
"generative_queries": 192,
"optimal": {
"weights": [
0.5,
0.0,
0.5,
0.0,
0.0,
0.0,
0.0,
0.0
],
"reward": 3.5,
"cost": 0.5
},
"optimal_incident_probability": 0.04999999999999999,
"estimated": {
"weights": [
0.68,
0.0,
0.31999999999999995,
0.0,
0.0,
0.0,
0.0,
0.0
],
"reward": 2.96,
"cost": 0.49999999999999994
},
"evaluation": {
"reward": 2.96,
"cost": 0.31999999999999995,
"violation": 0.0,
"incident_probability": 0.03199999999999999
},
"frontier": [
{
"budget": 0.0,
"solution": {
"weights": [
1.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0
],
"reward": 2.0,
"cost": 0.0
}
},
{
"budget": 0.25,
"solution": {
"weights": [
0.75,
0.0,
0.25,
0.0,
0.0,
0.0,
0.0,
0.0
],
"reward": 2.75,
"cost": 0.25
}
},
{
"budget": 0.5,
"solution": {
"weights": [
0.5,
0.0,
0.5,
0.0,
0.0,
0.0,
0.0,
0.0
],
"reward": 3.5,
"cost": 0.5
}
},
{
"budget": 1.0,
"solution": {
"weights": [
0.0,
0.0,
1.0,
0.0,
0.0,
0.0,
0.0,
0.0
],
"reward": 5.0,
"cost": 1.0
}
},
{
"budget": 2.0,
"solution": {
"weights": [
0.0,
0.0,
0.75,
0.0,
0.0,
0.25,
0.0,
0.0
],
"reward": 5.25,
"cost": 2.0
}
},
{
"budget": 5.0,
"solution": {
"weights": [
0.0,
0.0,
0.0,
0.0,
0.0,
1.0,
0.0,
0.0
],
"reward": 6.0,
"cost": 5.0
}
}
],
"dual": {
"last": {
"policy": [
0,
0,
0
],
"reward": 2.0,
"cost": 0.0
},
"average": {
"weights": [
0.37,
0.0,
0.625,
0.0,
0.0,
0.005,
0.0,
0.0
],
"reward": 3.895,
"cost": 0.65
},
"violating_iterates": 126
}
}每种子的经验解都满足样本预算,但真实成本不一定满足。下表保留全部八个种子;违约量为真实平均成本超过0.5的部分,不是单次事件数。
| 种子 | 真实奖励 | 真实平均成本 | 平均成本违约量 |
|---|---|---|---|
| 0 | 2.96000 | 0.32000 | 0.00000 |
| 1 | 2.96000 | 0.32000 | 0.00000 |
| 2 | 3.45714 | 1.00000 | 0.50000 |
| 3 | 3.30000 | 1.00000 | 0.50000 |
| 4 | 2.80000 | 0.80000 | 0.30000 |
| 5 | 3.60000 | 0.53333 | 0.03333 |
| 6 | 4.40000 | 0.80000 | 0.30000 |
| 7 | 3.20000 | 0.40000 | 0.00000 |
种子2的入口风险动作没有观察到事件。种子5、6得到比精确可行最优3.5更高的奖励,却通过超预算实现,不能报成更优的约束解。合适的比较必须同时看奖励、成本和约束定义。
即使用真实精确成本,对偶迭代也不是一路可行:200轮中126个策略超标,均匀混合这200个策略的成本0.65、奖励3.895,仍超过0.5。程序没有把它称为已收敛,也没有丢掉训练期违约。
枚举策略数D随状态数指数增长。当前朴素解算器创建O(D²)候选,却为每个候选保存D维稠密权重并逐项评分,最坏时间和存储为O(D³);本例D=8才便于直接核对。稀疏表示候选对可以改善这部分开销,但不会解决策略枚举的根本扩展问题。采样查询192次、优化200轮和评价用精确表,是三种不同成本。
成本模型漏掉的事,约束保不住
约束只能表达已定义的成本。若事件严重程度被低估,或代理指标与实际损失不一致,满足数学预算也不能推出满足业务要求。真实风险还可能随环境变化;本例固定概率不覆盖这种变化。
最终策略满足约束,不证明收集数据时的探索同样满足。可以使用规则控制器、动作过滤或保守回退作为对照与保护层,但它们也依赖模型与适用条件,不能只因名称叫“屏蔽器”就跳过验证。探索过程与外部知识
这里精确最优也允许5%事件概率,因为任务规定的是平均成本预算。若产品要求任何一次事件都不可接受,需要换约束和可行策略集合,不能靠润色“安全”二字解决。实际系统还应分别验证不可行时的行为、评测误差和资源约束;此处只提供合成教学计算。
别把三种风险混在一起
-
两策略的奖励/成本分别为2/0与5/1,平均成本预算0.5。怎样混合,得到多少奖励?
答案:每回合以1/2概率选各策略,平均成本0.5、平均奖励3.5。这里混合的是完整策略,不是参数向量;固定惩罚优化也未必自动选择恰好这个比例。
-
高成本策略以0.1概率产生一次成本10事件,其余成本0。上题混合策略是不是每回合成本都不超过0.5?
答案:不是。事件概率为0.5×0.1=0.05;发生时成本10,远超0.5,但期望仍为0.5。平均预算与逐轨迹上限不同。
-
λ=2、步长0.1、当前真实平均成本0.8、预算0.5。投影更新后λ是多少,为什么不是减小?
答案:2+0.1×(0.8−0.5)=2.03。超预算应增强成本惩罚;反向更新会鼓励继续违约。这个方向正确也不保证下一次或所有中间策略都可行。
-
种子6奖励4.4高于精确可行最优3.5,能否宣称学习算法超过了最优解?
答案:不能,因为真实平均成本0.8超过预算0.5。它不在同一可行集合中。应报告违约0.3,并同时保留包括没采到罕见事件在内的其他种子结果。
从安全定义读到实际误差
安全RL综述适合梳理是在改目标,还是在改探索,以及性能风险与硬限制的区别。分类框架 CPO适合逐层对照CMDP目标、理论界、可计算近似和恢复步骤,不应只引用摘要里的保证。原论文与实现条件
将方法用于新问题之前,先明确预算单位、评测分布和事件的含义。一个可以完整算清的小约束例子,能帮助发现大模型训练日志里被平均值遮住的区别。
先判断,再看解释
策略满足期望成本不超过0.5,能推出每次运行都不发生事件吗?
学习目标
- 写出奖励/成本/预算及不同安全定义,说明期望约束为何不等于逐轨迹无风险。
- 求解小CMDP并审计实际成本、有限对偶迭代与稀少样本导致的违约。
先修与延伸
查看知识关联图 →参考文献
- Constrained Policy Optimization — scoped ICML paper
Joshua Achiam; David Held; Aviv Tamar; Pieter Abbeel · 2017 - A Comprehensive Survey on Safe Reinforcement Learning — scoped taxonomy reading
Javier García; Fernando Fernández · 2015
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(AI)
Codex · 2026-09-24 · Single AI author. Scoped reading: PMLR70:22–31,10 pages; read2/5/6 and viewed5. Expected-cost CMDPs, distinction between conservative theoretical and practical approximate updates, Equations10–16, line search/recovery/cost upper bounds. No neural training or full-proof reproduction, and no pathwise-safety claim for sampled implementations. JMLR16:1437–1480,44 pages, published August2015 per first page. Read1/5 in full: objective versus exploration, worst-case/risk-sensitive/constrained criteria and training/deployment distinction. Other algorithms located only; no full-survey audit. Seven paired equations and four explained exercises. Exact two-stage policy mixtures checked against budget vertices and analytic frontier. All8 empirical models retain five true budget failures. Expected cost does not imply pathwise safety; dual average and last policy differ. Original finite model, not CPO or a deployment safety certificate.
- 精确两阶段策略混合以预算顶点和解析前沿核验。八个经验模型的五次真实超支保留;期望成本不保证逐轨迹安全,双重更新平均与末轮不同。原创有限模型,不冒称CPO或部署安全证书。
- 每题四张计算SVG,10数值/几何与18个当前响应式组合通过;九张当前选定图均直接实看,本组没有图形失败或捕获后资产修改,资产与稿件SHA绑定,完整页面验收另记。
核对的来源位置:
- Constrained Policy Optimization — scoped ICML paper · PMLR70:22–31,10 pages; read2/5/6 and viewed5. Expected-cost CMDPs, distinction between conservative theoretical and practical approximate updates, Equations10–16, line search/recovery/cost upper bounds. No neural training or full-proof reproduction, and no pathwise-safety claim for sampled implementations.
- A Comprehensive Survey on Safe Reinforcement Learning — scoped taxonomy reading · JMLR16:1437–1480,44 pages, published August2015 per first page. Read1/5 in full: objective versus exploration, worst-case/risk-sensitive/constrained criteria and training/deployment distinction. Other algorithms located only; no full-survey audit.
相关主题