Copy an expert who never slips, and the copy still gets lost. A clone that slips 2% of the time spends about 57 of 100 steps off the expert's data, not 2.
Pick an episode length and a slip rate, then press Roll out. Each line is one cloned robot. Red marks the steps it spends off the expert's data. Then we build, piece by piece, the language of decisions, the value of a state, the Bellman backup, and the reason copying breaks.
You need a little Python and what a probability is. We build the rest from zero.
Based on Lecture 5 of CMU 16-831, Introduction to Robot Learning, taught by Guanya Shi. Every idea is re-taught here in our own words and devices. It follows Lecture 4 and leads to Lecture 6.
Illustrative toy. Each step the clone slips with the chosen chance. After its first slip it is in states no demo covers and stays lost. Averages come from 400 runs; 14 are drawn.
Chapter 0
See why a robot that pays now and gets paid later must care about the future
A robot stands at one end of a hallway of six tiles, numbered 0 to 5. A charging dock waits past tile 5. Each move costs 0.1 units of battery. The move onto the dock pays 1.0. The robot may also stay where it is, which costs nothing.
Should it go? From tile 0 the trip is five paid moves, then one big payment. A robot that cares only about now sees five costs and stays. A robot that cares about later sees the payment and walks.
The knob for this is the discount, written γ (gamma): the value today of one unit of reward that arrives one step later. It runs from 0 to just under 1.
Each tile shows what the whole trip to the dock is worth from there. Green tiles walk, grey tiles stay. Slide the discount, then press Release.
Toy hallway: each move costs 0.1, the move onto the dock pays 1.0, staying pays 0. The trip values are exact for these numbers.
At γ = 0.5 the trip from tile 0 is worth −0.16. Staying is worth 0, so the robot stays. At γ = 0.9 the trip is worth +0.18, and the robot walks. The switch comes near γ = 0.81. Even a short-sighted robot walks from tile 4: one cost, then the dock, worth +0.4 at γ = 0.5.
Failure. A trained robot stands still near the start. Measure: compute what the trip is worth at the robot's γ. If it is below zero, staying is the right answer for that γ. Fix: raise γ or lower the step cost, so the goal is worth the trip.
The lecture has two halves. The first gives us the words to state this problem exactly. The second tries a shortcut, copying an expert, and finds the cliff in the hero.
Chapter 1
Write the hallway down as states, actions, a transition rule, rewards and a policy
To program the hallway robot, you must write the problem down. A Markov decision process (MDP) is the standard form for one agent that acts again and again. The lecture writes it as the tuple (S, A, p, r). The policy is what we learn, and the discount comes with the goal.
| Part | What it is | In the hallway |
|---|---|---|
| State space S | Every situation. One state s is a snapshot. | Tiles 0 to 5, and the dock |
| Action space A | Every move the robot can make. | left, stay, right |
| Transition p(s′ | s, a) | The world's rule for the next state. | right from tile 2 gives tile 3 |
| Reward r(s, a) | One number per step. Bigger is better. | −0.1 per move, +1.0 onto the dock |
| Policy π(a | s) | The robot's rule for picking an action. | always right |
Call the state at step t st and the action at. In general the next state could depend on the whole history. The Markov property says it does not: the present state and action are enough.
P of s-t-plus-one given s-zero, a-zero, and so on up to s-t and a-t, equals p of s-t-plus-one given s-t and a-t.
To predict the next state s-t-plus-one, look only at the state s-t and the action a-t. Throw the rest of the history away. The prediction does not change.
With a made-up slippery floor: from tile 3, the action right gives tile 4 with chance 0.9 and leaves the robot on tile 3 with chance 0.1. That is 0.9 whether the robot came from tile 2 or walked back from tile 5.
So a good state is a full summary of the past. A chess position is a state: you do not need the list of moves that made it. Choosing what goes into the state is half the work of setting up an MDP.
Press Step to move through one tick: the state feeds the policy, the action feeds the world, the world returns a new state and a reward. Switch to an observation to see a POMDP.
Toy loop on the hallway with the policy "always right". In observation mode the sensor reports the wrong neighbouring tile 3 times in 10 (made up).
A real robot rarely sees the state. A camera gives pixels, not "tile 3". It gets an observation o, made from the true state by an observation model h(o | s). That gives a partially observed MDP (POMDP): the tuple (S, A, O, p, h, r), with a policy π(a | o). This lesson assumes the robot sees the state; the POMDP Gleam drops that.
Failure. The robot acts well in one run and badly in another that starts from the same state. Measure: find two moments with equal states and different futures. Fix: add the missing information to the state, such as a velocity or the last two camera frames.
Chapter 2
Run one policy forward and get a different run each time
A policy maps a state to an action. A deterministic policy gives one action per state: "on tile 3, go right". A stochastic policy gives a chance for each action: right 0.8, left 0.2. We write it π(a | s), said "pi of a given s".
Now run the policy and the world together. The robot starts in s0, picks a0, gets reward r0, lands in s1, and so on. The list (s0, a0, r0, s1, a1, r1, …) is a trajectory, also called a rollout or an episode. It ends at the dock or after a set number of steps, the horizon T.
Each teal line is one run from tile 2: the tile on the way up, the step on the way across. Set the chance of going right, then press Sample.
Toy hallway, γ = 0.9, at most 30 steps. Left from tile 0 bumps the wall and costs a move.
With a chance of 1.0, every run from tile 2 is the same: four moves, and a return of 0.458 at γ = 0.9 (Chapter 3 shows the sum). At 0.8 the runs differ. Some take four moves, some take ten. One policy gives a spread of returns, so later chapters average over runs.
In code, a rollout is one loop. The data that flows: a state goes in, an action comes out, the world returns the next state and a reward.
pythondef rollout(policy, step, s, T=30, gamma=0.9): G, traj = 0.0, [] for t in range(T): a = policy(s) # state in, action out ('L' or 'R') s2, r, done = step(s, a) # the world: next tile, reward, at the dock? traj.append((s, a, r)) G += gamma**t * r # the return, built step by step s = s2 if done: break return traj, G
Failure. You score a stochastic policy on one rollout and report a lucky number. Measure: run 100 rollouts and look at the spread of returns. Fix: report the mean of many runs, with its spread.
Chapter 3
Turn a whole run into one number, and keep that number finite
A run earns a reward at every step. To say one policy is better than another, we need one number per run. So add the rewards, and shrink the late ones.
Call the reward at step t rt, and the discount γ. A reward t steps away is multiplied by γ once for each step of delay. The total is the return, G.
G equals the sum over t, from zero to T minus one, of gamma to the t times r-t.
Take each reward r-t. Multiply it by gamma once for every step you waited for it. Add the results. The total is G.
From tile 2, with γ = 0.9: four moves give r = −0.1, −0.1, −0.1, +1.0. G = −0.1 − 0.09 − 0.081 + 0.729 = 0.458. The dock's 1.0 counts as 0.729, because it comes three steps late.
The outline is each raw reward; the filled bar is what it counts after the discount. Pick a start tile and a discount, then press Unroll.
Toy hallway with the policy "always right". Values are exact.
There are two reasons. The first is meaning: a reward now beats the same reward later, and the far future is less sure. The second is maths. If a run can go on forever, an infinite horizon, then an undiscounted sum of rewards can grow without end. With γ below 1 it stays finite.
Call the largest size a single reward can have rmax. The worst case puts it at every step, forever.
The size of G is at most r-max divided by one minus gamma.
Put r-max at every step. The weights 1, gamma, gamma squared and so on add up to one divided by one minus gamma. So G can never pass r-max times that.
With r-max = 1: at γ = 0.9 the bound is 1 / 0.1 = 10. At γ = 0.99 it is 100. So 1 / (1 − γ) is also a rough look-ahead: about 10 steps at 0.9, about 100 at 0.99.
Failure. The robot ignores a goal that is 200 steps away. Measure: compare the task length with 1 / (1 − γ). Fix: pick γ so that look-ahead is longer than the task, such as 0.99 for a 100-step task.
Chapter 4
Score a state by the return you expect from it under one policy
The return scores one run. A robot standing on a tile wants a score for the tile: if I start here and follow my policy, what return do I get on average? That score is the value of the state.
Call the policy π and the start state s. If the policy or the world is random, the return changes from run to run. So we take its average over many runs, the expected value, written E.
V-pi of s equals the expected value, under pi, of the sum over t of gamma to the t times r-t, given that s-zero equals s.
Put the robot in state s. Run policy pi to the end, many times. Work out each run's return and average them. The average is V-pi of s.
With γ = 0.9 and π = always right, every run from tile 2 is the same, so Vπ(tile 2) = 0.458. With π = a coin flip, the robot wanders and pays for many moves: Vπ(tile 2) = −0.625.
Each bar is a tile's value under the chosen policy. Change the policy and watch the same tiles change worth.
Exact values for the toy hallway, found by the sweeps of Chapter 5. Left from tile 0 bumps the wall and costs a move.
Value is always value under a policy. Tile 2 is worth +0.46 under "always right" and −0.63 under the coin flip. Value also climbs toward the dock. That slope toward reward is what a learning robot follows.
A close cousin is the action value Qπ(s, a): take action a now, then follow π. It lets the robot compare "left here" with "right here". Q-learning is built on it.
Failure. The value estimates look right, yet the robot does badly. Measure: check which policy the values belong to. Fix: compute V for the policy you run. Values from one policy say little about another.
Chapter 5
Compute value from one step of reward and the value of the next tile
Averaging whole futures is slow. Here is the trick. The return from tile s is the first reward plus the discounted return from the next tile. So the value of s is the reward now plus γ times the value of where you land.
Take a deterministic policy in a deterministic world. Call the action the policy picks π(s), its reward r(s, π(s)), and the tile it lands on s′ (s-prime).
V-pi of s equals r of s and pi of s, plus gamma times V-pi of s-prime.
Take the reward r for this step. Add gamma times the value of the next tile s-prime. The sum is the value of this tile s.
With γ = 0.9, work backward from the dock. Tile 5: 1.0 + 0.9 × 0 = 1.0. Tile 4: −0.1 + 0.9 × 1.0 = 0.8. Tile 3: −0.1 + 0.9 × 0.8 = 0.62.
If the world or the policy is random, replace the next tile's value with its average over where you might land. The shape stays: this step's reward, plus a discounted look one step ahead.
At first you do not know V(s′). So guess 0 everywhere and apply the rule to every tile, again and again. One pass over all tiles is a sweep. Repeating sweeps until nothing changes is policy evaluation. With γ < 1, each sweep shrinks the largest error by at least a factor γ, so the values settle at a fixed point.
All values start at 0. Each sweep updates every tile from its neighbour's old value. The grey outline is the value before the sweep.
Toy hallway, policy "always right". Every tile updates from the values of the previous sweep.
In this hallway the reward travels back one tile per sweep, so six sweeps give the exact values. Now write the backup yourself.
Failure. The values keep changing or swing back and forth. Measure: print the largest change in each sweep; it should shrink by about γ each time. Fix: hold the end state at 0, and check that γ < 1 or that every run ends.
Chapter 6
Skip the reward and fit a policy to an expert's state and action pairs
Finding a good policy from reward is hard. It takes many trials, and someone must write the reward. The second half of the lecture tries a shortcut: record an expert, then copy.
Imitation learning learns a policy from demonstrations. Its simplest form is behavior cloning (BC): collect the expert's (state, action) pairs, then fit a function from states to actions with supervised learning. ALVINN, built at CMU in 1989, drove a van this way: road image in, steering angle out.
BC never sees the reward. It does not know the task is "stay in the lane". It knows only that in states like this, the expert did that.
Say a state is a list of d numbers, such as lane offset and heading, and the clone is linear: action = w · s. Stack the N demo states as the rows of a matrix S, shape N × d. Put the expert's actions in a vector a, length N. Least squares picks the weights w that make the squared error smallest. Setting its gradient to zero gives the normal equations.
W equals the inverse of S-transpose S, times S-transpose a.
Multiply each state feature by its action and add over the demos: that is S-transpose a. Multiply the features by each other and add: that is S-transpose S. Divide the first by the second to get w. With one feature, w is the sum of s times a over the sum of s squared.
With three made-up demos (s, a) = (1, 0.8), (2, 1.7), (−1, −0.9): the sum of s times a is 0.8 + 3.4 + 0.9 = 5.1, and the sum of s squared is 1 + 4 + 1 = 6. So w = 5.1 / 6 = 0.85. The clone steers 0.85 per unit of offset.
Blue dots are demos; the dashed blue curve is the expert's true rule. Purple is the clone. The teal line marks a test state at offset 2.5.
Made-up expert: steering = 0.85 × offset, capped at full lock ±1. Demos add a little noise. The clone is the one-feature fit above.
Near the centre the clone is excellent. At offset 2.5 it steers about 2.2 where the expert steers 1.0. The clone is only trustworthy where the demos are.
Failure. The clone matches held-out demos well and still fails on the robot. Measure: the error shows up only in states the robot reaches by itself. Fix: the next chapter explains why, and Lecture 6 gives the cures.
Chapter 7
See how the clone's own actions choose the states it is tested on
Supervised learning rests on one promise. Training and test examples are i.i.d.: independent, and drawn from the same distribution. Then low training error means low test error. An image classifier that gets photo 5 wrong does not change photo 6.
A robot breaks the promise, because its actions choose its next state. Call pdata(s) how often each state appears in the expert's demos. Call pπθ(s) how often each state appears when the clone drives.
P-pi-theta of s is not equal to p-data of s.
Count how often the expert visited each state: that is p-data. Count how often the clone visits each state: that is p-pi-theta. The counts differ, so an error measured on p-data says little about p-pi-theta.
From the toy below: the expert never leaves offsets between −0.3 and 0.3. A clone that slips 5% of the time spends 65% of its steps outside that range, where it has no training data at all.
Blue bars: lane offsets in the demos. Teal outline: offsets the clone visits. Red ground: offsets with no demos. Raise the slip rate, then add recovery demos.
Illustrative toy: 300 runs of 60 steps each. In its data, the clone steers back to the centre like the expert. Off its data it steers the wrong way and drifts. Recovery demos add expert slips and their corrections.
Why is the gap fatal? Experts rarely err, so the demos hold almost no states near the curb, and none of a recovery. The clone slips once and lands in a state no demo covers. It guesses, slips further, and never comes back. The lecture's phrase: statistically, imitation learning is cliff walking.
The toggle shows the lecture's twist. Demos that contain small mistakes and their corrections widen pdata, so the clone has seen the way back. At a 5% slip rate, time off the data falls from 65% to about 2%. Lecture 6 turns this into DAgger and data augmentation.
Failure. The clone drives well for ten seconds and fails after a minute. Measure: log the states it visits and count the share far from any demo state. Fix: collect expert labels in those states (DAgger), record recovery demos, or add noise during the demos.
Chapter 8
Count the lost steps and find a cost that grows with the square of the horizon
How bad is it? Ordinary supervised reasoning says: if the clone errs with chance ε per step, a run of H steps has about εH mistakes. The lecture says the real cost grows like H². One rule explains the gap: once lost, stay lost.
Call the slip chance per step ε (epsilon), the horizon H, and the number of steps the clone spends lost C. Step t is lost if any of the first t steps slipped. The chance of no slip in t steps is (1 − ε) multiplied by itself t times.
The expected value of C equals the sum over t, from one to H, of one minus, one minus epsilon, to the t. It is about epsilon H squared over two.
For each step t, find the chance the clone is already lost: one minus the chance it never slipped. Add these chances over all H steps. While slips are rare, step t is lost with chance about epsilon times t, and adding those up gives about epsilon H squared over two.
With made-up numbers ε = 0.01 and H = 20: the sum gives 1.97 lost steps, the short form gives 2.0, and the naive count εH gives 0.2. Compounding makes the cost ten times the naive guess.
Red dots are measured runs; the red curve is the sum above. Grey dashed is the naive εH, pink dotted is εH²/2. Set the slip rate and a horizon, then press Measure.
Illustrative toy: 300 runs per horizon, with the "once lost, stay lost" rule. The slip rate runs from 0.5% to 5% in steps of 0.5%.
The red curve bends up, as the square law says. Then it bends back toward the line C = H. Once εH passes about 1, almost every run is lost early, and a run cannot lose more steps than it has. So H² is the law of rare slips. Ross and Bagnell (2010) proved the worst case: BC's cost is at most the expert's plus εT². The imitation learning Gleam derives it.
Failure. Doubling the episode length more than doubles the failures. Measure: plot lost steps or failures against H on log axes; a slope near 2 means compounding. Fix: lower ε with better data, or change which states the clone learns on (Lecture 6).
Chapter 9
Keep the terms, the numbers, the code and the links in one place
An MDP states a decision problem as states, actions, a transition rule and rewards. A policy turns it into trajectories, the return scores a trajectory, and the value scores a state. The Bellman backup computes value one step at a time. Behavior cloning skips reward and copies an expert. It breaks the i.i.d. promise, so its cost grows like the horizon squared.
| Term | One line | Number to remember |
|---|---|---|
| MDP | The tuple (S, A, p, r); add O and h for a POMDP. | Hallway: 6 tiles, 3 actions |
| Markov property | The next state depends only on the state and action now. | 0.9 from tile 3, whatever the history |
| Return G | The sum of rewards, each shrunk by γ per step of delay. | 0.458 from tile 2 at γ = 0.9 |
| Look-ahead | 1 / (1 − γ) bounds the return and sets the reach. | 10 at 0.9, 100 at 0.99 |
| Value Vπ(s) | The expected return from s under π. | Tile 2: 0.46 always right, −0.63 coin flip |
| Bellman backup | Reward now plus γ times the next state's value. | Tile 4: −0.1 + 0.9 × 1.0 = 0.8 |
| Behavior cloning | Supervised fit from states to expert actions; no reward. | w = 5.1 / 6 = 0.85 |
| Distribution shift | The clone visits states the demos never show. | 65% of steps off the data at 5% slips |
| Compounding cost | Lost steps grow like εH²/2 while εH is small. | 57 of 100 steps lost at 2% slips |
pythonimport numpy as np def discounted_return(rewards, gamma): # Chapter 3 return sum(gamma**t * r for t, r in enumerate(rewards)) def evaluate_chain(rew, gamma, sweeps=100): # Chapter 5: tile i steps into i+1 V = np.zeros(len(rew) + 1) # last entry: the dock, held at 0 for _ in range(sweeps): V[:-1] = rew + gamma * V[1:] # one Bellman sweep, all tiles at once return V[:-1] def clone_linear(S, a): # Chapter 6: S is (N, d), a is (N,) return np.linalg.solve(S.T @ S, S.T @ a) # the normal equations, w is (d,) def expected_lost_steps(eps, H): # Chapter 8 t = np.arange(1, H + 1) return float(np.sum(1 - (1 - eps)**t)) print(discounted_return([-.1, -.1, -.1, 1.0], 0.9)) # 0.458 print(evaluate_chain(np.array([-.1]*5 + [1.0]), 0.9)) # 0.181 ... 0.8, 1.0 print(expected_lost_steps(0.02, 100)) # 57.5
Everything later in 16-831 either uses this MDP language or fights the cliff of Chapter 8. Reinforcement learning maximises the return directly. Imitation learning keeps copying but changes the data.
Based on Lecture 5, "MDP Basics and Imitation Learning, Part 1", of CMU 16-831, Introduction to Robot Learning, taught by Guanya Shi. The hallway, the toys and the worked numbers are our own.