A learning robot improves by trying things, and on a real robot some tries break it. A safety filter sits between the policy and the motors. It edits only the actions that would cross the line, so the robot keeps out of danger on every step.
Turn the filter off and on. Watch the greedy policy drive through the person, then curve around them. Then we build, piece by piece, why a crash penalty is not enough, how a budget and a barrier work, and why the filter can promise "never".
You need state, action and reward (Lecture 5) and a little vector geometry. We build the rest from zero.
Lecture 22 of 25 in Introduction to Robot Learning, CMU 16-831 (Spring 2024), taught by Guanya Shi. Slides on the course lectures page. Every idea is re-taught here in our own words and devices. Next: Lecture 23, Multi-Task, Adaptive and Transfer Learning.
Illustrative toy. The policy always heads straight for the goal at 1.2 m/s (purple arrow). The filter keeps the rate of change of the distance to the circle above −γ times that distance (Chapter 6) and sends the teal arrow to the motor.
Chapter 0
Let a noisy learner walk along a table edge, and see what a reset costs on a real robot
An agent that learns Atari dies thousands of times. Each death costs nothing: the game resets and the agent tries again. Trial and error works because failure is free.
Now put the same learner on a quadruped that walks along a table edge. The first fall breaks an actuator. The robot cannot collect more data, because it is in pieces. Some states are catastrophic: once the robot enters one, the damage cannot be undone.
The robot walks right toward the yellow goal. Its early policy jerks sideways. Press Run for 20 tries, then turn the filter on and run the same 20 tries again.
Illustrative toy. Try k gets the same random jerks with the filter on and off, so the two runs are a fair comparison. The filter limits the sideways speed to 3 times the distance left to the edge.
With the filter off, more noise means more falls. With it on, the same noisy policy never falls. The learning still happens. The catastrophe does not.
The symptom is a robot that is fine in simulation and breaks itself in its first real hour. To measure it, count how often exploration visits a state you cannot recover from. The fix in this lecture is a layer between the policy and the motors that refuses those actions.
Chapter 1
Write safety as a constraint, sort it into two kinds, and grade it on three strengths
The lecture makes "safety" precise in one sentence: safety is a constraint in an MDP. The robot still minimizes a cost over time. Safety adds a region the state may not enter and a set of actions the robot may not use.
Call the state at step t x-t and the action (the control) u-t. Call the cost paid at that step c-t, and the rule that moves the world to the next state f-t, the dynamics. Call the set of allowed states X-t, the safe set, and the set of allowed actions U-t.
Minimize the sum over t of c-t of x-t and u-t, subject to x-t-plus-one equals f-t of x-t and u-t, x-t in X-t, and u-t in U-t.
Find actions u-t with the smallest total cost. Only plans where every state x-t is in X-t and every action u-t is in U-t count. The last two conditions are the safety part.
With made-up numbers: the robot is 2.0 m from the edge, X is "distance at least 0" and U is "speed at most 1 m/s". The action u = −0.8 m/s for 1 s gives 1.2 m: allowed. The rule throws out any plan that ends at −0.3 m, whatever it costs.
The lecture sorts safety constraints into two kinds:
| Kind | It asks | Example |
|---|---|---|
| State-wise | Does the state ever enter a forbidden region? | Collision avoidance; staying 1 m from a person |
| Policy-wise | After a small push, does the robot come back? | Stability: a drone hit by a gust returns to its path |
It also grades how strong a guarantee is:
Each dot is one run, placed at its closest approach to the wall. Red dots crossed the wall. Pick a level.
Illustrative toy. Every level uses the same 200 random draws, closest approach = centre + 0.12 m times a draw. Encourage centres at 0.15 m, probabilistic at 0.246 m (2% tail), hard clips every run at the wall.
The symptom is a method sold as "safe" that still crashes now and then. To measure it, ask which kind of constraint it enforces and at which level. The fix is to pick the level the task needs: hard near people, encourage where a violation is cheap.
Chapter 2
Raise the crash penalty and watch the crash rate shrink but never reach zero
The first instinct is: "Give the robot a big negative reward for a crash. RL will learn to avoid it." RL maximizes expected return, the average total reward over many runs. The penalty is one term inside that average, so the optimizer is free to trade it.
Take a toy. The robot picks its aggression a, from 0 (crawl) to 1 (full speed). A run pays 10 times a in reward. Call the crash penalty P, and the chance of a crash in one run p(a). Here p(a) = 0.2 times a cubed: faster driving crashes more often. Call the expected return J(a).
J of a equals ten times a, minus P times p of a.
For each aggression a, take the reward 10 times a and subtract the penalty P times the crash chance p(a). The optimizer picks the a with the largest J(a). A crash is a cost to weigh, not a wall.
P = 100: the best a is 0.41, and p(a) is 1.36%, so about 136 crashes in 10,000 runs. P = 10,000: the best a is 0.041, and p(a) is 0.00136%. Fewer crashes, a crawling robot, and still not zero.
Where does the best a come from? J(a) is largest where its slope is zero. The slope of 10a − 0.2Pa³ is 10 − 0.6Pa². Set it to zero:
Any finite P gives an a* above 0, so p(a*) stays above 0.
Top: the expected return J(a) and the optimizer's pick. Bottom: the crash chance at that pick for every penalty, on log scales. Slide the penalty.
Illustrative toy: reward 10a per run, crash chance 0.2a³, aggression a from 0 to 1. The bottom line falls with slope −1.5 and never touches zero.
There is a second problem. RL learns that a state is bad by visiting it. To learn "this crash is worth −P", the robot must crash. The penalty asks the robot to learn the danger by meeting it.
The symptom is a policy that "almost never" crashes, and a manager who asks for a bigger penalty. To measure it, plot the crash rate against P on log scales: it falls along a line and never hits zero. The fix is a separate constraint: a budget (Chapter 3) or a filter (Chapter 6).
Chapter 3
Keep reward and cost apart, set a budget, and let a multiplier find the price of safety
A hand-picked penalty is a guess. A constrained MDP (CMDP) keeps two signals apart. It maximizes reward, subject to a budget on a second signal: the cost of unsafe behaviour.
Call the task reward at step t r-t, and the safety cost at step t c-t. The cost fires on unsafe behaviour, such as coming within 1 m of a person. Call the discount γ, a number below 1, and the budget d.
Maximize over pi the expected value of the sum over t of gamma to the t times r-t, subject to the expected value of the sum over t of gamma to the t times c-t being at most d.
Score each policy π twice: its average discounted reward and its average discounted cost. Throw out every policy whose cost is above the budget d. Of the rest, keep the one with the most reward.
With made-up numbers, 3 steps and γ = 0.9. Policy A: rewards 1, 1, 1 and costs 0, 1, 0, so reward 2.71 and cost 0.9. Policy B: rewards 1, 1, 0.5 and no cost, so reward 2.305. With d = 0.5, the budget rules A out and B wins.
The budget d has a meaning: "at most 0.5 near misses per run, on average". It limits an average, so CMDPs are Level I.
The standard solver folds the constraint back in with a price that learns. Call the expected reward R(π), the expected cost C(π) and the price λ (lambda), the Lagrange multiplier. The policy maximizes L = R(π) − λ(C(π) − d), and λ moves with a step size η (eta):
Lambda becomes the max of zero and lambda plus eta times C minus d.
If the cost C is over the budget d, raise the price λ by η times the excess. If C is under d, lower λ, but not below zero. Then let the policy re-optimize at the new price.
In the device's toy, η = 0.15 and d = 0.3. At λ = 0 the policy runs flat out with cost 1.5, so λ becomes 0 + 0.15 × 1.2 = 0.18, then 0.36, then 0.51. After about 23 rounds λ settles at 0.745 and the cost sits at 0.30.
Warm: the cost each round. Green dashes: the budget. Pink: the price λ. Press Play, then try a large step size.
Illustrative toy from the Code Lab below: reward a, cost 1.5a², aggression a from 0 to 1. At each price the policy picks a = 1/(3λ), capped at 1.
The symptom is a cost that swings around the budget forever: at η = 3 it jumps between about 0.15 and 0.45. To measure it, plot the cost per round. The fix is a smaller step size, or averaging the policies over rounds.
Chapter 4
Slide the safety margin and trade reward against the chance of a crash
RL improves by exploration: trying actions it is unsure about. To know if an action is safe, you usually try it. But trying an unsafe action is the catastrophe you must not have. This chicken-and-egg problem is safe exploration.
The usual answer keeps a known-safe set: states the robot is sure it can survive and recover from. It explores only at the edge of that set and grows it with care, like a climber roped to a ledge.
The price is the central trade-off of the lecture: conservatism versus performance. The best reward often lives near the edge. The fastest racing line hugs the wall.
Make it a number. The robot aims a margin m short of a wall, and noise spreads its position around the aim. Call the chance of crossing the wall in one step q, and the number of steps in a run T.
Risk equals one minus, one minus q, to the power T.
One step is safe with chance 1 − q. The whole run is safe only if all T steps are, so multiply 1 − q by itself T times. The risk is what is left.
With made-up numbers: position noise 0.1 m and margin m = 0.3 m give q = 0.00135. Over T = 50 steps the risk is 6.5%. At m = 0.4 m, q = 0.00003 and the risk is 0.16%.
Top: the corridor, the reward growing toward the wall, and where the noisy robot lands. Bottom: reward and risk for every margin. Slide the margin.
Illustrative toy: reward 10 × (1 − m) per step, Gaussian position noise 0.1 m, 50 steps per run.
Look at the shape. Reward rises in a straight line as the margin shrinks. Risk stays near zero, then shoots up. The methods in the rest of the lecture find and certify the smallest margin that is still safe.
The symptom is a margin tuned in a few test runs that crashes in week two. To measure it, compute the risk over the full deployment length T, not per step. The fix is a guarantee that does not depend on luck: the barrier function, next.
Chapter 5
Limit how fast the robot may approach danger, and the limit turns into a promise
Define one number for each state, the safety function h(x). It is 0 or more when the state x is safe and below 0 when it is not. The wall is where h(x) = 0. Think of h as a signed distance to danger.
Checking "h is 0 or more right now" is not enough. The robot can be safe now and moving so fast that no action can stop it in time. So we limit how fast h may fall. Call the rate of change of h, its speed, h-dot. Call a positive constant γ (gamma) the barrier rate.
H-dot of x is at least minus gamma times h of x.
The robot may approach danger at most γ times as fast as its distance h. Far away it may rush. Close in it must crawl. At h = 0 it may not approach at all.
With γ = 1 per second: at h = 2 m, h-dot may go down to −2 m/s. At h = 0.5 m, down to −0.5 m/s. At h = 0, h-dot must be 0 or more: no crossing.
A function h with this rule, where some action can always meet it, is a control barrier function (CBF). The rule promises more than it seems. If h starts positive and the robot obeys it, h can shrink at most like a falling exponential:
The exponential never reaches zero, so the robot never leaves the safe set. This is forward invariance: start safe, obey the rule, stay safe for all time.
Top: the allowed region (green) above the pink limit −γh. Bottom: the distance h over time. The robot wants 2 m/s. Press Play, then change γ.
Illustrative toy: start at h = 2.5 m, the robot asks for 2 m/s toward the wall, and h-dot = max(−2, −γh). Time step 0.01 s.
The symptom is a "brake at 1 m" rule that goes through the wall when the robot arrives fast. To measure it, find the fastest approach your rule allows at each distance. The CBF limit shrinks smoothly to zero at the wall, so no arrival speed is too late.
Chapter 6
Let the policy propose, then send the motor the nearest action that obeys the barrier
Now use the barrier. The policy does what it wants. A safety filter checks each action and edits only the unsafe ones. The policy and the guarantee are separate parts, so any policy can sit behind the same filter.
Call the proposed action u-nom, any candidate action u, and the chosen action u-star. The search in step 3 is a small optimization:
U-star equals the arg-min over u of the squared distance from u to u-nom, subject to h-dot of x and u being at least minus gamma times h of x.
Of all actions u that obey the barrier rule, pick the one nearest to u-nom. If u-nom obeys the rule, u-star is u-nom. The filter changes nothing until the robot nears the wall.
A robot 2.0 m from a wall, h = p = 2.0, action = velocity v, so h-dot = v. With γ = 1 the rule is v ≥ −2.0. The policy asks for −3.5 m/s; the nearest allowed value is v* = −2.0. A request of −1.0 passes unchanged.
This is the CBF-QP of Ames and colleagues (2017). It is a quadratic program: a squared-distance objective with a linear constraint, when h-dot is linear in u. It has a few variables and solves fast enough to run at the robot's control rate. In one dimension it is a clip: v* = max(v-nom, −γp).
Top: the robot, the purple request and the teal command. Bottom: position over 6 s, with and without the filter. Set the request, then press Play.
Illustrative toy: start at p = 2.0 m, time step 0.05 s, the policy repeats the same request every step.
This is a real deployment pattern. The lecture's case study, Safe Deep Policy Adaptation (ICRA 2024), trains its policy in simulation and wraps it in a CBF-QP filter on the real robot.
The filter is only as good as its model of h-dot. The symptom is a robot that crosses the wall while the filter reports "safe". To measure it, log the predicted and the real h-dot. The fix is a margin for model error, or a learned correction with a bound (Chapter 8).
Chapter 7
Place a goal behind a person, and watch the filter bend a greedy path around them
A robot drives in a 2D arena. A circular keep-out zone (a person) sits in the middle with centre c and radius R. The policy is greedy: it drives straight at the goal, even through the person.
The safety function is the distance to the circle's edge: h(x) = ‖x − c‖ − R. Call the unit vector from the centre to the robot n. Moving along n raises h one for one, so h-dot = n · v, the part of the velocity v that points away from the centre. The filter keeps the sideways part and fixes only that part:
In words: if the robot approaches the centre faster than γh allows, add just enough outward speed to meet the floor. The sideways speed stays, so the robot slides around the circle.
Tap the arena to place the goal, or pick a preset. Purple is the policy's request, teal is what the motor runs. The strip at the bottom traces h over time.
Illustrative toy: centre (0, 0), radius 1 m, speed 1.2 m/s, time step 0.03 s, at most 14 s per run.
Set the goal behind the circle and toggle the filter. Off, the robot drives through the red zone. On, the teal arrow peels away from the purple one at the edge and curves around. The policy never changed. Only the filter acted, and only where it had to.
Pick "Dead behind". The goal sits exactly behind the centre, so the request has no sideways part. The filter cancels the inward part and the robot stops on the edge: a deadlock. To measure it, flag a speed near zero with the goal unreached. The fix is a small sideways nudge or a planner that picks a side.
Chapter 8
Push the robot, watch an energy number fall or grow, and see why a learned model needs a leash
The other kind of safety is policy-wise: stability. Push the robot a little off its path. Does the gap shrink or grow?
| Strength | After a push, the gap |
|---|---|
| Stable | stays bounded |
| Asymptotically stable | shrinks to zero |
| Exponentially stable | shrinks at least as fast as a falling exponential |
For a linear closed loop x-next = A x, the test is the spectral radius ρ (rho): the largest size of an eigenvalue of A. If ρ is below 1, every gap shrinks each step.
Simulating every push is hopeless in high dimensions. A Lyapunov function V(x) avoids it: an energy-like number, positive everywhere except 0 at the target. Call its rate of change V-dot, and a positive rate α (alpha).
V-dot of x is at most minus alpha times V of x.
Check one local rule: at every state, the energy V falls at a rate of at least α times V. Then V(t) ≤ V(0) e to the −αt, and the robot returns to the target exponentially. No simulation needed.
With made-up numbers: V = 4 and α = 0.5 per second, so V-dot must be −2 or lower. After 2 s, V ≤ 4 × e−1 = 1.47.
A barrier and a Lyapunov function are twins: one number per state, and a local rule on its derivative. The barrier says "h may not fall past the wall". The Lyapunov function says "V must fall toward the goal".
Left: the gap after a push, step by step. Right: the energy V = gap squared. Set the feedback gain, then press Push.
Illustrative toy: x-next = (1.2 − K) times a rotation by 0.45 rad, applied to x. So ρ = |1.2 − K| and V shrinks by ρ² per step.
Near the ground, a landing drone feels a ground effect that is hard to model. Neural-Lander (Shi and colleagues, ICRA 2019) learns that force with a deep network and feeds it to the controller. The stability proof needs a bound on the network's Lipschitz constant: how fast its output can change as its input changes.
Unconstrained, the network can be steep and the guarantee is lost. Spectral normalization bounds the Lipschitz constant, so the proof holds and the drone lands smoothly.
Two more tools from the lecture. Hamilton-Jacobi reachability finds the states from which a crash is unavoidable and keeps the robot out of them; the Agile But Safe work uses it on a fast quadruped. Reach-avoid value networks learn a value whose sign says if a state can reach the goal safely.
The symptom is a controller with a learned term that works in tests and oscillates on hardware. To measure it, estimate the network's Lipschitz constant, or push the closed loop and watch V. The fix is a bound on the learned part, as in Neural-Lander.
Chapter 9
Keep the terms and numbers, a checklist and the safety filter in code
Safety is a constraint in an MDP: state-wise or policy-wise, enforced at one of three strengths. A penalty only encourages. A CMDP budget is Level I done properly. A barrier function and its filter give the hard level, and a Lyapunov function certifies stability.
| Term | One line | Number to remember |
|---|---|---|
| Safety | A constraint in an MDP: x in X, u in U. | Levels I, II, III |
| Reward trap | A penalty is a price; the crash rate never hits zero. | P 100: 1.36%; P 10,000: 0.00136% |
| CMDP | Max reward subject to expected cost at most d. | A: 2.71 with cost 0.9, out at d 0.5 |
| Multiplier | λ ← max(0, λ + η(C − d)). | Settles at 0.745, cost 0.30 |
| Run risk | 1 − (1 − q) to the T. | m 0.3: 6.5% over 50 steps |
| CBF | h-dot ≥ −γh. | h 2, γ 1: floor −2 m/s |
| Safety filter | Nearest action that obeys the barrier. | −3.5 becomes −2.0 |
| Lyapunov | V-dot ≤ −αV. | V 4, α 0.5: 1.47 after 2 s |
pythonimport numpy as np def cbf_filter(u_nom, h, a, b, gamma=1.0): """One barrier, h_dot = a @ u + b. Returns the u nearest u_nom with h_dot >= -gamma*h.""" slack = a @ u_nom + b + gamma * h # >= 0 means u_nom is already safe if slack >= 0: return u_nom # the filter changes nothing return u_nom - slack * a / (a @ a) # project onto the constraint plane def dual_step(lam, cost, budget, eta=0.15): return max(0.0, lam + eta * (cost - budget)) # the CMDP thermostat # 1D wall: h = p, h_dot = v -> a = [1], b = 0 print(cbf_filter(np.array([-3.5]), h=2.0, a=np.array([1.0]), b=0.0)) # [-2.]
With several barriers or motor limits, the projection has no closed form. Use a small QP solver at each control step.
This lesson follows Lecture 22, Safe RL and Safe Robot Learning, of CMU 16-831 Introduction to Robot Learning, Spring 2024, taught by Guanya Shi. The slides are on the lectures page. The CBF-QP is from Ames and colleagues (2017) and Neural-Lander from Shi and colleagues (ICRA 2019). The tables, arenas and their numbers are our own toys.
Now press Present or Teach and explain from memory: why a penalty is not a guarantee, what the multiplier does, and why h-dot ≥ −γh keeps the robot safe forever. Then go back to the arena, slide γ, and say why the path changes but never enters the circle.