Foundations to Frontier
Tests

Safe reinforcement learning and constrained MDPs

Safe reinforcement learning keeps an agent within limits on harm while it learns and when it is deployed. The standard formulation is the constrained MDP: maximise reward subject to a bound on expected cost. Its solution comes from a Lagrangian, may need a randomised policy, and is learned by primal–dual methods; shields and safety filters add hard protection during training. This page solves a hazard gridworld exactly, then compares fixed penalties, primal–dual learning, a PID Lagrangian and a shield.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Getting there without breaking things

A delivery robot could cut across a busy pavement to save time, or go round. A single score that mixes speed and collisions forces a guess about how many collisions a minute is worth. A safer way to state the goal is ‘be as fast as possible, but collide less than once a month’. Safe reinforcement learning works with goals stated like that, and also tries to avoid breaking things while the robot is still learning.

Reinforcement learning lab
→
→
→
→
→
→
↓
↑
↑
↑
→
→
→
↓
↑
↑
→
→
→
→
G
↓
↓
↓
→
→
→
↑
→
→
→
→
→
→
↑
A 5×7 grid, start at the left middle (bold arrow), goal G (+1), −0.02 per move, each move slips sideways with probability 0.1, γ = 0.95. Entering an orange hazard cell costs 1, a separate signal from the reward. Arrows: the optimal policy for reward − λ·cost with λ = 0.1; its reward value is 0.4360 and its expected discounted hazard cost 0.1785 (within the limit d = 0.2). Ignoring cost gives 0.6203 at cost 2.845. The constrained optimum for d = 0.2: λ* = 0.0745; mixing the two greedy policies on either side of λ*, with weight 0.186 on the riskier one, reaches cost exactly d and value 0.4376. Larger λ buys safety with reward: the route bends around the hazard, and at very large λ even the slips next to it are avoided.
Why engineers care

Constraints appear in robotics (force and collision limits), autonomous driving, data-centre cooling, finance (risk limits) and language-model alignment, where helpfulness is maximised subject to harmlessness.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Safe RL states goals as…
  2. 2. Mixing speed and collisions into one score requires…
  3. 3. Safety matters during…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Constrained MDP (CMDP, Altman 1999): an MDP with a cost signal c(s, a) besides the reward; maximise V_r(π) subject to V_c(π) ≤ d, where V_c is the expected discounted cost.
  • Lagrangian: L(π, λ) = V_r(π) − λ(V_c(π) − d) with multiplier λ ≥ 0. For fixed λ, maximising L is an ordinary MDP with reward r − λc.
  • Randomised optimal policies: the best feasible policy may have to mix two deterministic policies, because a cost limit can fall between what deterministic policies achieve.
  • Primal–dual learning: improve the policy on L while raising λ when the constraint is violated and lowering it otherwise.
  • PID Lagrangian (Stooke, Achiam and Abbeel 2020): add proportional and derivative terms to the λ update to damp oscillation and overshoot.
  • Constrained policy optimisation (CPO, Achiam et al. 2017): a trust-region step that keeps the cost estimate within the limit.
  • Shields and safety filters: block or correct unsafe actions before they reach the environment (Alshiekh et al. 2018; control barrier functions; safety layers).
  • Risk-sensitive criteria: constrain the tail of the cost, such as its conditional value at risk (CVaR), not only its mean.
📝 Quick check (Level 1)
0/3 answered
  1. 1. A CMDP maximises reward subject to…
  2. 2. For fixed λ the Lagrangian problem is an MDP with reward…
  3. 3. A shield…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

A hazard grid solved exactly

Exercise 1.

  • A 5 × 7 grid: start at the left middle, goal at the right middle (+1, ends the episode), −0.02 per move, γ = 0.95. Each move slips to a side with probability 0.05 each.
  • A 3 × 3 hazard block sits on the direct route; each entry into a hazard cell costs 1, a separate signal. The limit is d = 0.2 on the expected discounted cost from the start.
  • The Lagrangian solution: the greedy policy for r − λc is found by value iteration; bisection finds the λ* where its cost crosses d, and the two policies on either side of λ* are mixed once per episode so the cost is exactly d.
  • All values and costs are exact (linear solves).

Practice.

  • Specify costs separately from rewards whenever a limit is meaningful (collisions, energy, risk); it removes the guesswork of penalty weights.
  • Use a Lagrangian method as the default: PPO-Lagrangian or SAC-Lagrangian with a PID-controlled multiplier; tune the cost limit, not a penalty.
  • Expect training-time violations: primal–dual methods only satisfy the constraint on average after convergence. Add a shield, safety filter or conservative initial policy if early violations are unacceptable.
  • Budget for exploration: the constraint applies to the behaviour policy, so exploration noise itself costs; the multiplier rises to pay for it.
  • Tools: Safety-Gymnasium environments and the OmniSafe library of constrained algorithms.
def lagrangian_solution(P, R, C, s0, gamma, d, iters=40):
    vc = lambda lam: evaluate(P, C, greedy_policy(P, R - lam * C, gamma), gamma, s0)
    lo, hi = 0.0, 1.0
    while vc(hi) > d: hi *= 2
    for _ in range(iters):                         # bisection for λ*
        mid = (lo + hi) / 2
        lo, hi = (mid, hi) if vc(mid) > d else (lo, mid)
    p_lo = greedy_policy(P, R - lo * C, gamma)     # slightly too risky
    p_hi = greedy_policy(P, R - hi * C, gamma)     # feasible
    c_lo, c_hi = vc(lo), vc(hi)
    w = (d - c_hi) / (c_lo - c_hi)                 # mix to hit d exactly
    return (lo + hi) / 2, w, p_lo, p_hi
🐍 Exercise 1: the Lagrangian solution of a CMDP
Build the hazard grid, find λ* by bisection, mix the two neighbouring deterministic policies to meet the cost limit exactly, and compare with ignoring the cost.
📝 Quick check (Level 2)
0/3 answered
  1. 1. A good default constrained algorithm is…
  2. 2. Why do primal–dual methods violate constraints while training?
  3. 3. A benchmark suite for safe RL is…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Lagrangian duality for CMDPs. Optimising over occupancy measures (the discounted state–action frequencies of policies), both V_r and V_c are linear and the set of achievable occupancies is convex, so the CMDP is a linear program. Strong duality holds when a strictly feasible policy exists: max_π min_(λ≥0) L(π, λ) = min_(λ≥0) max_π L(π, λ). The optimal λ* is the slope of the reward–cost frontier at d: the reward that one more unit of allowed cost would buy.

Why mixing is needed. For fixed λ, the inner maximisation has a deterministic optimal policy, but at λ* several policies tie, with costs on both sides of d. The CMDP optimum is the mixture that meets the limit exactly; an occupancy-measure LP has at most one more randomised state than there are constraints (Altman 1999).

Primal–dual dynamics. Gradient ascent on π and descent on λ is a game between the policy and the multiplier. Integral-only (dual ascent) control of λ reacts to accumulated violation, so it lags and overshoots; adding a proportional term reacts to the current violation and damps the cycle, which is the motivation for the PID Lagrangian.

Shields and barriers. A shield computes, from a model, which actions can lead to unsafe states and removes them, guaranteeing safety during learning up to the accuracy of the model. A discrete control barrier function h(x) ≥ 0 on the safe set is kept positive by requiring h(x_(t+1)) ≥ (1 − κ)h(x_t), so the state may approach the boundary but never cross it.

📝 Quick check (Level 3)
0/3 answered
  1. 1. λ* equals…
  2. 2. At λ*, the optimal policies for r − λ*c…
  3. 3. A proportional term in the λ update…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

How do fixed penalties, primal–dual learning, a PID Lagrangian and a shield trade off reward, constraint satisfaction and violations during training?

History.

  • E. Altman (1999) wrote the standard theory of constrained MDPs, including the LP and Lagrangian approaches.
  • J. García and F. Fernández (2015) surveyed safe RL; J. Achiam, D. Held, A. Tamar and P. Abbeel (2017) introduced constrained policy optimisation.
  • C. Tessler, D. Mankowitz and S. Mannor (2019) introduced reward-constrained policy optimisation; A. Stooke, J. Achiam and P. Abbeel (2020) introduced PID Lagrangian methods.
  • M. Alshiekh and colleagues (2018) introduced shielding; G. Dalal and colleagues (2018) introduced safety layers; A. Ames and colleagues (2019) reviewed control barrier functions.
  • A. Ray, J. Achiam and D. Amodei (2019) released Safety Gym.

Exercise 2, part 1: exact primal–dual learning.

  • Tabular softmax policy, exact natural-gradient steps θ ← θ + 0.2(A_r − λA_c), and λ updated each iteration from the violation e = V_c − d: dual ascent (λ accumulates 0.05e) or a PID Lagrangian with a proportional term 2e. 3,000 iterations from the uniform policy; this part is deterministic.
  • The proportional term removed most violations: dual ascent spent 17 iterations with cost above 0.21, the PID Lagrangian 2. Both converged to the constrained optimum: final values 0.4370 and 0.4374 against 0.4376.

Exercise 2, part 2: learning from samples.

  • Q-learning of separate reward and cost values (α = 0.1, ε = 0.1), acting greedily on Q_r − λQ_c, 500 episodes, 5 runs. The final greedy policy’s value and cost are computed exactly. The primal–dual learner updates λ by 0.05 times the episode’s discounted cost minus d; the shield blocks moves whose intended direction enters a hazard.

Seed 0, means over 5 runs (constrained optimum 0.4376 at cost 0.2):

method hazard entries in training final value final cost runs within d final λ
reward only 2,300 0.5911 3.2747 0 0
fixed λ = λ* = 0.0745 418 0.4297 0.2667 2 0.0745
fixed λ = 1 329 0.4136 0.1374 5 1
primal–dual 293 0.2507 0.1054 5 1.655
shield 174 0.4209 0.2250 1 0
  • Ignoring cost gave the most reward and about 2,200 to 2,300 hazard entries per run on all seeds; no final policy met the limit.
  • The exact λ was fragile:* greedy deterministic policies cannot mix, and small value errors decide which side of d they land on; 2, 3 and 4 of 5 runs met the limit on seeds 0, 1 and 2.
  • Primal–dual learning was over-cautious: the ε-greedy behaviour policy’s own cost stayed above d (0.24 to 0.26 in the last 100 episodes), so λ kept rising, to 1.6 to 2.1, and the final greedy policies were worth only 0.10 to 0.25.
  • A conservative fixed penalty (λ = 1) worked best here: every run on every seed met the limit, at a value of 0.408 to 0.414.
  • The shield halved training violations (170 to 179 entries, all from slips) but its learned policies hug the hazard and met the limit in only 0, 1 and 1 of 5 runs: blocking deliberate entries is not the same as bounding expected cost.
🐍 Exercise 2 (research): how do fixed penalties, primal–dual learning, a PID Lagrangian and a shield trade off reward, constraint satisfaction and violations during training?
Solve the hazard-grid CMDP exactly, then compare dual ascent and a PID Lagrangian with exact gradients, and Q-learning with no cost, fixed penalties, primal–dual λ and a shield, measuring reward, final cost and violations during training.

Safe RL in practice

  • Robotics: learned policies run behind safety filters (control barrier functions, model-predictive safety layers) and are trained in simulation before deployment (topic L6-4).
  • Autonomous driving: rule-based shields and formal verification check learned planners against traffic rules.
  • Language models: helpfulness and harmlessness are trained with separate reward and cost models, and Safe RLHF (Dai et al. 2024) uses a Lagrangian to balance them.
  • Risk-aware RL: CVaR and distributional critics limit rare catastrophic outcomes rather than average cost.

References

  1. E. Altman (1999). “Constrained Markov Decision Processes.” Chapman and Hall.
  2. J. Achiam, D. Held, A. Tamar and P. Abbeel (2017). “Constrained policy optimization.” ICML.
  3. A. Stooke, J. Achiam and P. Abbeel (2020). “Responsive safety in reinforcement learning by PID Lagrangian methods.” ICML.
  4. M. Alshiekh, R. Bloem, R. Ehlers, B. Könighofer, S. Niekum and U. Topcu (2018). “Safe reinforcement learning via shielding.” AAAI.
  5. J. García and F. Fernández (2015). “A comprehensive survey on safe reinforcement learning.” JMLR.