Safe RL: why can an expected budget still allow incidents?
安全强化学习
Compare exact policy mixtures, empirical costs and dual updates, distinguishing expected budgets, individual risk and training violations.
safe-rlAcceptable on average is not incident-free every time
A controller handles most tasks well but occasionally produces a large loss. Its average reward can look good while it fails a requirement that every trajectory remain within limits. “Safe” must be specified through costs, events, probabilities and time horizons before an algorithm can know what to preserve.
Safe reinforcement learning studies learning and decisions subject to performance or risk requirements. One approach changes the objective, such as constraining expected cost or emphasizing worst outcomes. Another changes exploration, for example through external knowledge or execution restrictions. An acceptable final policy and a training process that never takes risks need separate evidence. Safety objectives and exploration
Our events are explicitly fictional numeric events: each occurrence costs ten, with no real robot or person at risk. In a two-step task, the optimal mixture meets expected cost 0.5 yet still has a five-percent incident probability. We calculate it exactly and retain learning results that meet empirical budgets but violate true ones.
Specify what the constraint actually constrains
A constrained Markov decision process (CMDP) adds costs and budgets to rewards. Below we use finite horizon H; appropriate discount assumptions also permit an infinite horizon. Fix units and signs rather than mixing higher-is-better rewards with lower-is-better costs. CMDP definition
These are expected constraints. Two other requirements bound the probability of exceeding a limit or require the limit to hold on almost every trajectory. Writing cumulative trajectory cost as Cτ, these are different statements:
The first alone does not specify the other two. Nonnegative costs can support additional probability bounds, but a threshold and event definition are needed. Discounted costs also downweight distant incidents. If the requirement is never entering a state, merely discounting its distant loss does not express that requirement.
In our known finite model, enumerate eight deterministic policies and choose one at random at the start of each episode, executing it throughout. Each policy has exactly calculable expected reward Rj and cost Cj. The single-budget problem becomes a linear program over mixture weights:
Linearity comes from mixing complete episodic policies, not arbitrarily averaging neural-network parameters. One budget plus the probability-sum constraint permits an optimal vertex with at most two positive weights. The program checks feasible individual policies and pairs straddling the budget, without a hidden optimizer. For lower-cost policy a and higher-cost policy b, b’s weight is:
Two effective endpoints among the eight policies have reward 2/cost 0 and reward 5/cost 1. Mixing them equally at budget 0.5 yields reward 3.5/cost 0.5. The latter has a 0.1 probability of an incident costing ten, leaving mixture incident probability 0.05. Feasible deterministic policies achieve at most reward two, so randomization matters here.
Large unknown environments cannot enumerate all policies. Lagrangian methods often adjust the tradeoff between reward and cost. For one constraint, the policy maximizes L while a nonnegative multiplier increases in response to budget excess. Dual updates and training-time limitations
A fixed penalty need not deliver the desired budget, and a dynamic multiplier does not make every intermediate policy feasible. The sign matters: exceeding the budget increases lambda, subtracting more cost from the next objective. Finite optimization, approximation and sampling errors can still leave violations.
CPO uses constrained policy updates. A small-step approximation linearizes reward and cost and approximates policy distance quadratically. Let Δ be the parameter change, g the reward gradient, bi a cost gradient, ci current budget excess and H local KL curvature:
The paper distinguishes a conservative theoretical update, trust-region approximation, sample estimates, line search and infeasibility recovery; its approximate constraint result also has an error term. An algorithm name is not a pathwise incident-free certificate. Our program does not implement CPO: it uses an exactly solvable problem to expose constraint meanings and finite-step dual behavior. Equations 10–16 and practical implementation
Rare events complicate cost estimation. For independent queries with true incident probability p, the chance of observing none in n samples is:
For p=0.1 and n=32, this is about 3.43%, not zero. A zero count does not prove zero true cost or policy safety. This calculation assumes identically distributed independent queries; nonstationary environments require a different analysis.
Check empirically feasible policies against true costs
The original two-step task has three decision states. The entry action determines the next state. Action zero at each state earns one without incidents; entry action one earns two with incident probability 0.1. At the second stage, action one earns four, with incident probability 0.1 or 0.4 depending on the entry route. Incidents do not change transitions, but each adds cost ten. Episodes are finite and undiscounted.
First compute the exact optimal mixture as a reference. Then query each state-action pair thirty-two times, totaling 192 generative queries, and solve using sample costs. Rewards are known; true costs are used only to evaluate the empirical solution. Separately, run two hundred rounds of exact reward-minus-penalty best response followed by a projected multiplier update, retaining every iterate.
"""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))
Inspect the recorded summary
{
"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
}
}Every seed’s empirical solution meets the sample budget, but not necessarily the true budget. All eight seeds are retained. Violation is true expected cost in excess of 0.5, not the number of individual incidents.
| Seed | True reward | True expected cost | Expected-cost violation |
|---|---|---|---|
| 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 |
Seed two observes no incidents for the risky entry action. Seeds five and six exceed the exact feasible optimum of reward 3.5 by violating the budget, not by finding better constrained solutions. A valid comparison examines reward, cost and the definition of the constraint together.
Even exact true costs do not make dual iterates uniformly feasible. Of two hundred iterates, 126 exceed the budget. A uniform mixture of all those policies has cost 0.65 and reward 3.895, still violating 0.5. The program does not call this converged or discard training-time violations.
The number D of deterministic policies grows exponentially with states. This naive solver constructs O(D²) candidates but stores a dense D-dimensional weight vector for each and scores every coordinate, giving worst-case O(D³) time and storage. D=8 makes it inspectable here. Sparse policy-pair candidates could reduce that overhead without solving the fundamental enumeration problem. The 192 sample queries, two hundred optimization rounds and exact-table evaluation are separate costs.
Constraints cannot protect what the cost model omits
A constraint expresses only its defined cost. Underestimated severity or a proxy that differs from actual loss can make a mathematical budget irrelevant to business requirements. Risk can also change with the environment; these fixed probabilities do not test that change.
A feasible final policy does not establish feasible exploration. Rule-based control, action filters or conservative fallback can provide baselines and protective layers, but each depends on a model and scope. Calling something a shield does not remove the need to validate it. Exploration and external knowledge
Even the exact optimum here permits five-percent incident probability because the specified requirement is an expected-cost budget. If a product cannot tolerate any incident, its constraint and feasible policy set must change; polishing the word “safe” cannot fix the mismatch. Real systems also need separate checks of infeasibility behavior, evaluation error and resources. This example supplies synthetic teaching calculations only.
Keep three risk statements separate
-
Two policies have reward/cost pairs 2/0 and 5/1, with expected-cost budget 0.5. How should they be mixed, and what reward results?
Answer: Choose each at the start of an episode with probability one-half, yielding cost 0.5 and reward 3.5. This mixes complete policies, not parameter vectors. A fixed penalty does not necessarily select exactly that proportion.
-
The higher-cost policy has a 0.1 chance of a cost-ten incident and otherwise costs zero. Does the mixture keep every episode below cost 0.5?
Answer: No. Incident probability is 0.5×0.1=0.05; an incident costs ten, far above 0.5, while expectation remains 0.5. Expected budgets and pathwise limits differ.
-
Lambda is two, learning rate 0.1, current true expected cost 0.8 and budget 0.5. What is the projected update, and why not decrease lambda?
Answer: It becomes 2+0.1×(0.8−0.5)=2.03. Budget excess should strengthen the cost penalty; reversing the sign encourages violations. The correct direction still does not guarantee feasibility of the next or every intermediate policy.
-
Seed six earns 4.4, above the exact feasible optimum 3.5. Has learning surpassed the optimum?
Answer: No. Its true cost 0.8 exceeds budget 0.5, placing it outside the same feasible set. Report violation 0.3 and retain all other seeds, including those that missed rare incidents.
Read from the safety definition to practical error
The survey helps distinguish changes to objectives from changes to exploration, and performance risk from hard limits. Taxonomy CPO supports a layer-by-layer comparison of CMDP objectives, theoretical bounds, computable approximations and recovery, rather than relying on the abstract’s guarantee language. Paper and implementation conditions
Before applying a method elsewhere, specify budget units, evaluation distribution and event meaning. A completely calculable small constraint problem helps reveal distinctions hidden by averages in larger training logs.
Make a prediction, then check
Does expected cost at most 0.5 imply that every execution is incident-free?
Learning objectives
- Specify rewards, costs, budgets and safety definitions, explaining why expected constraints are not pathwise guarantees.
- Solve a small CMDP and audit true costs, finite dual iterates and violations caused by limited samples.
Prerequisites & connections
Explore related knowledge →References
- 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
Version1 · Editorial status: Recorded technical checks completed
View technical check record (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.
- 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.
- Four computed SVG variants per topic;10 numeric/geometry tests and18 current responsive cases passed. All nine selected current captures directly viewed; no figure failure or post-capture asset edit in this group. Actual assets and manuscripts are SHA bound. Full article acceptance recorded separately.
Source locations checked:
- 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.
Related topics