Copy an expert's actions and you copy only the states the expert visited. One small slip puts the copy where no demo went, and the errors grow: in the worst case with the square of the episode length.
Learn to train a policy from demonstrations, see why it drifts, and fix the drift and the averaging trap, with every equation read aloud.
Watch the cloned car hold the teal band where the expert drove. Press Nudge and it leaves the band, where it has no data, and runs off the road. Then pick + corrective labels and nudge again. Then we build it piece by piece: cloning, compounding, DAgger, expressive policies and action chunking.
You need a little Python and what a probability is. We build the rest from zero.
Re-taught from Lecture 2, Imitation Learning, of Stanford CS 224R: Deep Reinforcement Learning. The explanations, toys and numbers here are our own; every toy number is illustrative.
Illustrative toy. The car drives at 7 m/s on a road 3.6 m wide, 30 steps per second. The demos cover offsets within 0.35 m and heading errors within 0.16 rad. Inside that band the clone steers like the expert; outside it, it has no example, so it holds its heading. A slip turns the car by 0.13 rad; a nudge by 0.3 rad. Corrective labels cover the band out to 1.7 m.
Chapter 0
Record an expert, and see how thin a band of states the recording covers
You want a car to stay in its lane on a winding road. Writing a reward for that is hard. How bad is 10 cm off centre, next to a jerky turn? Driving the road yourself is easy. So you drive it, record what you did, and train a network to copy you.
That is imitation learning: learning a policy from an expert's demonstrations, with no reward. A policy, written π (pi), maps a state to an action. The state s is the situation: here, the car's offset from the lane centre. The action a is what the policy does: here, the steering. A demonstration is one recorded run, the state and the expert's action at each step.
Each teal line is one demo: the expert's offset over 100 steps. The bars on the right count the states at each offset. Add demos and watch where the bars grow.
Illustrative toy road, 4 m wide from edge to edge. The expert pulls back 35% of its offset each step, and wind and small slips push it about.
With numbers: 5 demos of 100 steps give 500 (state, action) pairs. Nearly all of them sit within 0.3 m of the centre. The expert is good, so it never visits the edges, and the data never shows what to do there.
The failure. The data looks complete, but it covers a thin band. The symptom is a model that scores well on held-out demos and still leaves the road. To measure it, plot where the training states sit beside where the policy goes. The fixes are Chapters 3 and 4.
Chapter 1
Treat each state as an input and the expert's action as its label, and fit a network
Take every (state, action) pair from the demos. The state is the input. The expert's action is the label. Fit a network that maps one to the other. That is behaviour cloning (BC): supervised learning on demonstrations. It needs no reward and no simulator, and the car never drives during training.
Name the parts. The network has weights θ (theta), and the policy it computes is π-theta. The dataset D holds N pairs. The loss L measures how far each prediction lands from the expert's action.
L of theta equals one over N times the sum, over pairs s and a in D, of the squared distance between a and pi-theta of s.
Run each state s through the network. Subtract its guess pi-theta of s from the expert's action a, and square the gap. Average over all N pairs. Gradient descent turns θ to make L smaller.
With made-up numbers: the expert steered −12°, 5° and 0°, and the network said −10°, 6° and 1°. The squared gaps are 4, 1 and 1, so L = 6 / 3 = 2.
Each teal dot is one demo pair: offset in, steering out. The warm line is the clone, steering = gain × offset. Drag the gain, or press Gradient step.
Illustrative toy: 60 pairs from an expert who steers −20° per metre of offset, plus noise with a spread of 1.5°. Each step moves the gain by 8 times the gradient.
The failure. A low loss is not good driving. The loss checks only states in the data, all within 0.3 m of the centre. Past the last dot, the line is a guess nobody checked. The symptom is a validation loss near the noise floor and a car that leaves the road. To measure it, run the policy and log the states it reaches, not only the loss. The fix comes in Chapter 3.
Chapter 2
Follow one slip into states the data never showed, and bound how fast the cost grows
Your clone matches the expert 99 steps in 100. On step 30 it steers 2° too far. Now it sits 0.4 m off centre, where no demo went. Its next action is a guess, so the next state is stranger still.
This is distribution shift: the training states come from the expert, but at test time the clone's own mistakes choose its states. Each slip moves it further from the data, so the errors feed each other. They compound. The hero shows it: one nudge, then no way back.
How fast can the cost grow? Give each step a cost of 1 if the policy does not do what the expert would, and 0 if it does. Call the expected total cost over an episode J. The expert's total is J of π-star, the clone's is J of π-hat. The episode has T steps. The clone's mistake rate on the expert's own states is ε (epsilon).
J of pi-hat is at most J of pi-star plus T squared times epsilon.
The chance of a first slip by step t is at most t times epsilon. In the worst case, every step after that slip costs 1. Add those chances over all T steps and you get about T squared times epsilon.
With made-up numbers: epsilon = 0.01. For T = 10 the extra cost is at most 1. For T = 50 it is at most 25, half the steps. For T = 100 it reaches 100, so the worst case is a mistake on every step.
Ross and Bagnell (2010) proved this bound for behaviour cloning. The lecture states the same growth: order epsilon times T squared. Double T and the ceiling grows four times.
Each row is one rollout. It is teal while it stays on the expert's states and turns yellow after its first slip, because it never finds its way back. The bars compare the average cost with the bound.
Illustrative toy: a slip happens with chance ε on each step on the expert's states; after it, every step costs 1. The middle bar is the exact average for this toy; the rows are 24 samples.
The failure. The symptom is a policy that works on short tasks and falls apart on long ones. To measure it, plot success against episode length; a curve that drops faster than a straight line points here. The fixes are data from the states the policy visits (Chapter 3) and a shorter effective T (Chapter 8).
Chapter 3
Let the clone drive, ask the expert what it would do there, and train on the result
The clone fails in states the expert never visited. So let the clone drive, record the states it reaches, and ask the expert to label each one. That is DAgger, dataset aggregation (Ross, Gordon and Bagnell, 2011).
The clone chooses where to go; the expert chooses what to do there. After a few rounds, D holds expert actions for the clone's own mistakes, so the clone learns to recover.
Left: the clone's latest drive, offset over time. Right: the data at each offset, teal for expert demos and purple for DAgger labels, with the clone's steering as a small arrow. Press Run a round.
Illustrative toy. The clone is a lookup table. Each 0.2 m bin of offset steers by the average label it holds; an empty bin returns a fixed random guess. Each round is one drive of up to 150 steps.
How much does this help? Call u the recovery cost: how much one wrong action can raise the expert's future cost. Now ε is the clone's mistake rate on the states it visits itself.
J of pi-hat is at most J of pi-star plus u times T times epsilon.
At every step the clone slips with chance epsilon, and each slip costs at most u. The training data covers the states after a slip, so a slip does not poison later steps. The costs add, so they grow with T, not T squared.
With made-up numbers: epsilon = 0.01, T = 100 and u = 2. The ceiling is 2 × 100 × 0.01 = 2 extra mistakes. Plain cloning's ceiling at the same epsilon and T was 100.
The failure. DAgger needs an expert on call. A person must label strange states without driving the car, which is hard. The symptom is noisy labels in odd states. To measure it, have two people label the same states and count how often they agree. The fix is to let the expert drive the hard parts, next chapter.
Chapter 4
Take over only when the clone heads for trouble, and pick how to collect the demos
Nobody wants to label 10,000 frames of a robot flailing. In HG-DAgger, human-gated DAgger (Kelly et al., 2019), the expert watches the clone drive and takes over only when it heads for trouble. The expert drives back to safety, and that takeover becomes new training data.
The warm line is the clone driving; purple is the expert after a takeover. The dashed lines are your takeover distance. The expert reacts 3 steps after the car crosses the line. Drive, then drive again.
Illustrative toy: the same lookup-table clone as Chapter 3, starting from 3 expert demos. The road edge is 2.0 m from the centre.
With numbers from the toy: at 0.9 m, the first drive needs one takeover and labels 8 of 300 states. The second needs one more; the third needs none. The expert spent time only where the clone needed help.
The failure. Timing is a skill. Take over too late and the car crashes before the expert recovers; set the distance to 1.9 m and watch. Take over too early, at 0.3 m, and the expert steps in three times as often, on states the clone could handle. To measure it, log the offset at each takeover and the share of states labelled.
| Method | How it works | Good at | Hard part |
|---|---|---|---|
| Kinesthetic teaching | Move the robot arm by hand | Direct and easy to learn | Awkward for fast or two-arm motions |
| Teleoperation | Drive the robot with a joystick or VR controller | Works for any robot | Lag, and the operator needs practice |
| Puppeteering | Move a matching leader arm; the robot follows | One-to-one, precise | Twice the hardware |
| Human video | Learn from people doing the task | Huge amounts of data | A hand is not a gripper |
The last row is the embodiment gap: the body in the data differs from the robot's body. Driving and text have natural demos at scale. Robot demos are scarce, often hundreds per task.
Chapter 5
See why squared error turns two good actions into one bad average
A box sits in the lane. Three demos swerve left: −20°, −18° and −21°. Two swerve right: +22° and +19°. Both ways are fine. What does the clone from Chapter 1 do?
Name the parts. At this one state there are n demos, with actions a-1 to a-n. The clone must output one action, a-hat. Squared error picks the a-hat that makes the sum of squared gaps smallest.
A-hat-star is the a-hat that makes the sum over i of a-i minus a-hat, squared, smallest. It equals one over n times the sum over i of a-i.
Score each candidate a-hat by the squared gaps to every a-i. The slope of that score is minus two times the sum of a-i minus a-hat. It is zero when a-hat is the mean.
With the demos above: (−20 − 18 − 21 + 22 + 19) / 5 = −18 / 5 = −3.6°. No demo steered near −3.6°. The car drives into the box.
Teal paths are the five demos. The blue path is the squared-error clone: the mean steering. Change how many demos go left.
Illustrative toy: left demos steer −20, −18, −21, −19 and −22 degrees; right demos +22, +19, +20, +21 and +18. Any steering within 8° of straight hits the box.
The failure. The symptom is a low training loss and a policy that drives into the middle of two good options, or freezes between them. To measure it, plot the demo actions at one state; two clumps mean trouble. The fix is an output that can hold two clumps.
Chapter 6
Output a probability for every action, so the policy can say left or right but not straight
Let the policy output a probability for every action. Then it can say "left 60%, right 40%, straight almost never" and sample. Train it to raise the log-probability of each expert action.
A single Gaussian (a bell curve) does not help: its one peak sits on the mean. A mixture of Gaussians adds several bells. The network outputs, for each bell k of K, a weight w-k, a centre μ-k (mu) and a spread σ-k (sigma).
Pi-theta of a given s equals the sum over k of w-k times the normal density of a, with centre mu-k and spread sigma-k squared.
Draw K bells, each centred on one good action mu-k with width sigma-k. Scale each by its share w-k and add them. The result can have a peak at every good action and a valley between.
With made-up numbers: K = 2, shares 0.6 and 0.4, centres −20° and +20°, spread 3°. At −20° the density is 0.080 per degree. At 0° it is about 0.00000000003.
Teal ticks are 50 demo actions at one state. The warm curve is the fitted policy. The red band is the box. Press Draw 20 samples.
Illustrative toy: 30 demos near −20° and 20 near +20°, spread 2.5°. We fit the mixture with 40 rounds of expectation maximisation. The bins are 33 equal slices of −40° to +40°.
A second way is discretisation: cut each action dimension into bins and predict a probability for each bin, as a classifier does. For an arm with several dimensions, predict them one at a time, each given the ones before, as a language model predicts words.
Pi of a given s equals p of a-one given s, times p of a-two given s and a-one, and so on, up to p of a-D given s and every earlier dimension.
Pick a bin for dimension 1 from its probabilities. Feed that choice back in and pick dimension 2. Repeat to dimension D. Multiply the chances to get the chance of the whole action.
With made-up numbers: steering "left 20°" has chance 0.6; given left, speed "slow" has 0.9; together 0.54. For 7 joints with 256 bins each, one big table would need 2567, about 7.2 × 1016 outputs. One dimension at a time needs 7 × 256 = 1,792.
| Output head | Two clumps? | Catch |
|---|---|---|
| One number (squared error) | No: predicts the mean | The averaging trap |
| One Gaussian | No: one peak | Peak at the mean, wide spread |
| Mixture of K Gaussians | Yes, up to K | You choose K in advance |
| Bins, one dimension at a time | Yes | Bin width limits precision |
| Diffusion or flow | Yes, any number | Many passes per action |
The failure. Too few bells merge two clumps; wide bins make jerky control. The symptom: samples that miss the demo clumps. To measure it, compare a histogram of many samples at one state with the demos. More bells or finer bins fix it.
Chapter 7
Start from random noise and move it, step by step, into an action
A diffusion or flow policy moves random noise, in small steps, into an action. Different noise ends in different clumps, so it holds any number of good actions without a chosen K. The state plays the part of an image model's text prompt.
Here is the flow version. Take an expert pair: state s and action a. Draw noise x-0 from a standard bell curve. Pick a time t between 0 and 1, and mix: x-t = t × a + (1 − t) × x-0. The straight line from x-0 to a moves with velocity a − x-0. A network v-theta looks at x-t, s and t, and guesses that velocity.
L of theta equals the average, over t, x-zero and pairs s and a, of the squared distance between v-theta of x-t, s and t, and a minus x-zero.
Pick a demo pair, a noise x-0 and a time t. Mix a and x-0 into x-t. Ask v-theta for the velocity there, and score it against a minus x-0, squared.
In units of 20°, with made-up numbers: a = −1 (that is −20°), x-0 = 0.5 and t = 0.25. Then x-t = −0.25 + 0.375 = 0.125, and the target is −1.5. If v-theta says −1.2, the squared error is 0.09.
To act, start from fresh noise and take K small steps from t = 0 to t = 1. Each step moves x a K-th of the way along v-theta:
Pink dots start as noise on the left. Each path follows the velocity to the right edge, t = 1. Teal ticks are the five demos from Chapter 5; the red band is the box.
Illustrative toy: the velocity field is the exact best one for these five demos, not a trained network, so samples land on the demos themselves. Noise has a spread of 20°.
Try 1 step. Every sample lands on −3.6°, the mean. At t = 0 the noise says nothing about which demo it came from, so the best velocity points at the average: the averaging trap again. More steps let each sample commit to a clump.
Diffusion Policy (Chi et al., 2023) trains the network to predict the added noise instead of a velocity. It is the same idea with a different target. The robot model π0 (Physical Intelligence, 2024) uses flow matching.
The failure. Each step is one network pass. Too few steps blur the clumps; too many make the robot slow. To measure it, time one action and count the clumps in the samples as you change K. The next chapter buys the time.
Chapter 8
Predict the next k actions at once, so the policy commits and has time to think
A robot at 50 Hz picks a new action every 20 ms. A policy that samples a fresh action each time can pick left, then right, then left. Action chunking predicts the next k actions at once and runs them before it predicts again.
Chunking gives two things:
The warm path is the robot passing a box. Each dot is a new prediction, which samples left (60%) or right (40%). Switch on the push and see how long the robot takes to respond.
Illustrative toy: 40 steps at 50 Hz. Within a chunk the robot plays its planned moves open loop, so a push is not corrected until the next prediction.
The cost is reaction time. Inside a chunk the robot does not look. A push at the start of a chunk waits up to k − 1 steps: for k = 8 that is 7 steps, or 140 ms.
ACT (Zhao et al., 2023) eases this with temporal ensembling: it predicts a chunk at every step and averages the overlapping predictions for each step. Diffusion Policy also predicts a sequence and runs only part of it before it predicts again.
The failure. The symptom is a robot that ignores a bump until its chunk ends. To measure it, time from a disturbance to the first correcting action. The fix is a shorter chunk, more frequent predictions, or temporal ensembling.
Chapter 9
Add a reward to cloning, so the policy can copy the good demos and pass the expert
Plain cloning copies every demo equally, the clumsy ones too. It can never beat the expert. Reinforcement learning (RL) can, but it needs a reward and many tries. The two fit together.
| Property | Imitation | RL |
|---|---|---|
| Needs a reward | No | Yes |
| Needs demos | Yes | No |
| Can beat the expert | No | Yes |
| Data needed | Little: supervised | Much: must explore |
Four common ways to join them:
For the second way, call the return of demo i R-i, the total reward it earned. A temperature β (beta) sets how picky the copying is. Each demo gets a weight w-i in the cloning loss.
W-i equals e to the power R-i over beta.
Divide each demo's return R-i by beta, and take e to that power. Multiply that demo's squared errors by w-i. Demos that earned more pull the clone harder.
With made-up numbers: beta = 2, returns 2 and 9. The weights are e1 = 2.72 and e4.5 = 90.0, so the better demo counts 33 times as much.
Each bar is one demo; its height is its share of the cloning loss. Lower beta and watch the share move to the best demos.
Illustrative toy: six demos with returns 2, 4, 5, 6, 8 and 9. We assume the clone earns the weighted average return of what it copies.
With six demos of return 2, 4, 5, 6, 8 and 9, plain cloning expects (2 + 4 + 5 + 6 + 8 + 9) / 6 = 5.67. At beta = 2 the weighted clone expects 7.83.
The failure. At a tiny beta the clone copies one demo and learns its noise. To measure it, compute the effective number of demos: one over the sum of the squared weight shares. At beta = 0.5 it is 1.27. The fix is a larger beta, or the advantage in place of the return (Peng et al., 2019), so a lucky start does not count. The offline RL lesson continues this line.
Chapter 10
Keep the terms, the numbers, a checklist and the core code on one page
Behaviour cloning is supervised learning on an expert's (state, action) pairs. It has two enemies. The first is drift: one slip leads to states the data never showed, and the cost can grow with T squared. DAgger fixes it with labels on the clone's own states. Averaging: two good actions make a bad mean; an output that holds a distribution fixes it. Chunking buys commitment and time, and a reward lets the clone pass the expert.
| Term | Meaning |
|---|---|
| Behaviour cloning (BC) | Supervised learning from states to the expert's actions |
| Distribution shift | Test states differ from training states, because the policy's mistakes pick them |
| DAgger | The clone drives, the expert labels the visited states, retrain on everything |
| HG-DAgger | The expert takes over when needed; takeovers become data |
| Averaging trap | Squared error predicts the mean of several good actions |
| Mixture of Gaussians | K weighted bell curves: one peak per good action |
| Flow policy | Moves noise into an action along a learned velocity |
| Action chunk | The next k actions, predicted at once and run open loop |
| What | Number | Why it matters |
|---|---|---|
| Cloning bound, ε = 0.01, T = 50 | at most 25 extra | Grows with T squared |
| DAgger bound, ε = 0.01, T = 100, u = 2 | at most 2 extra | Grows with T |
| Mean of −20, −18, −21, +22, +19 | −3.6° | Into the box |
| Bins for 7 joints × 256 | 1,792 outputs, not 7.2 × 1016 | Predict one dimension at a time |
| Chunk k = 8 at 50 Hz | 160 ms per prediction | Time for 10 flow steps |
| Return-weighted clone, β = 2 | 7.83 against 5.67 | A reward lets you copy the best |
Cloning is one supervised loop. DAgger wraps it: the policy drives, and the expert labels.
pythonimport torch def train_bc(policy, states, actions, epochs=50, lr=1e-3): # states [N, obs_dim], actions [N, act_dim]: the expert's pairs opt = torch.optim.Adam(policy.parameters(), lr=lr) for _ in range(epochs): loss = ((policy(states) - actions) ** 2).sum(-1).mean() # L(theta) opt.zero_grad(); loss.backward(); opt.step() return policy def dagger(env, expert, policy, demo_states, demo_actions, rounds=5): S, A = list(demo_states), list(demo_actions) for _ in range(rounds): train_bc(policy, torch.stack(S), torch.stack(A)) # retrain on all of D s, done = env.reset(), False while not done: S.append(s); A.append(expert(s)) # the expert labels the state with torch.no_grad(): a = policy(s) # but the clone drives s, done = env.step(a) return policy
Now press Present or Teach and explain from memory why a clone drifts, how fast the cost can grow, and what DAgger changes. Then go back to the hero, nudge the car with demos only and with corrective labels, and say what the purple band added.
This lesson re-teaches Lecture 2, Imitation Learning, of Stanford CS 224R: Deep Reinforcement Learning. The papers behind it: Ross and Bagnell (2010), the T squared bound; Ross, Gordon and Bagnell, DAgger (2011); Kelly et al., HG-DAgger (2019); Chi et al., Diffusion Policy (2023); Zhao et al., ACT (2023); Ho and Ermon (2016), GAIL; Peng et al. (2019), advantage-weighted regression. The toys and numbers here are our own.