Imitation Learning

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.

Nudge the cloned car off its data

2.5%

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

Teaching by Showing

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.

Record the expert

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.

5

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.

The road

  1. Behaviour cloning: copying is supervised learning.
  2. Small errors compound: the hero's drift, and the T squared bound.
  3. DAgger: the hero's corrective labels, collected for real.
  4. Humans in the loop: takeovers, and where demos come from.
  5. The averaging trap: two good actions make one bad average.
  6. Mixtures and bins: outputs that hold two options.
  7. Diffusion and flow policies: noise moved into an action.
  8. Action chunking: predict several steps, then commit.
  9. Imitation plus reward: going past the expert.
  10. The field guide: terms, numbers, code and links.
What does one demonstration contain?

Chapter 1

Behaviour Cloning Is Supervised Learning

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.

Say it aloud

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.

L(θ)
L of theta the loss: how badly the network with weights θ copies the expert.
(1/N) Σ(s,a)∈D
one over N times the sum over pairs in D add one term per recorded pair, then divide by the N pairs.
a
a the expert's action in that pair: the label.
πθ(s)
pi-theta of s the network's action for state s: the prediction.
‖ · ‖2
the squared distance the gap between two actions, squared, so big misses count more.
In plain words

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 numbers

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.

Fit the clone

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.

0.0

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.

Which of these does behaviour cloning need during training?

Chapter 2

Small Errors Compound

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).

Say it aloud

J of pi-hat is at most J of pi-star plus T squared times epsilon.

J(π̂)
J of pi-hat the clone's expected total cost over one episode.
≤
is at most a worst-case ceiling, not a forecast.
J(π*)
J of pi-star the expert's expected total cost.
T2
T squared the episode length in steps, times itself.
ε
epsilon the chance the clone errs on a state from the expert's data: its held-out error rate.
In plain words

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 numbers

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.

Watch the slips add up

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.

1.0%
50

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).

Epsilon stays at 0.01. The episode doubles from 50 to 100 steps. What happens to the bound on the extra cost?

Chapter 3

DAgger: Label the States the Clone Visits

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).

  1. Train the policy on the expert's demos, the dataset D.
  2. Run the policy. Record every state it visits.
  3. Ask the expert for its action in each recorded state.
  4. Add the new pairs to D. Keep the old ones.
  5. Retrain on all of D, and go back to step 2.

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.

Run DAgger rounds

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.

Say it aloud

J of pi-hat is at most J of pi-star plus u times T times epsilon.

J(π̂)
J of pi-hat the DAgger policy's expected total cost.
≤
is at most a worst-case ceiling, after enough rounds.
J(π*)
J of pi-star the expert's expected total cost.
u
u the recovery cost: the most one wrong action can add to the expert's cost from there on.
T
T the episode length in steps. Not squared now.
ε
epsilon the clone's error rate on its own states, the ones DAgger labelled.
In plain words

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 numbers

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.

During a DAgger rollout, whose action moves the car, and whose action is stored as the label?

Chapter 4

Humans in the Loop

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.

  1. The clone drives. The expert watches.
  2. When the clone looks unsafe, the expert takes control and recovers.
  3. Add the takeover segment to D, and retrain.

Choose when to grab the wheel

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.

0.9 m

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.

Where demos come from

MethodHow it worksGood atHard part
Kinesthetic teachingMove the robot arm by handDirect and easy to learnAwkward for fast or two-arm motions
TeleoperationDrive the robot with a joystick or VR controllerWorks for any robotLag, and the operator needs practice
PuppeteeringMove a matching leader arm; the robot followsOne-to-one, preciseTwice the hardware
Human videoLearn from people doing the taskHuge amounts of dataA 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.

The expert takes over only when the car is 1.9 m from the centre of a 2.0 m half-road. What goes wrong?

Chapter 5

The Averaging Trap

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.

Say it aloud

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.

â*
a-hat-star the best single action under squared error.
argminâ
the a-hat that makes it smallest try every one-number answer and keep the winner.
Σi
the sum over i one term for each of the n demos at this state.
ai
a-i the steering angle of demo i, in degrees.
(1/n) Σi ai
one over n times the sum of a-i the mean of the demo actions.
In plain words

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 numbers

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.

Average two good swerves

Teal paths are the five demos. The blue path is the squared-error clone: the mean steering. Change how many demos go left.

3 of 5

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.

At one state the demos steer −10°, −10° and +30°. What does a squared-error clone output?

Chapter 6

Mixtures and Bins

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).

Say it aloud

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.

πθ(a | s)
pi-theta of a given s how likely the policy is to pick action a in state s.
Σk
the sum over k one term per bell, from 1 to K.
wk
w-k the share of bell k; the shares add to 1.
𝒩(a; μk, σk2)
the normal density of a, centre mu-k, spread sigma-k a bell curve around one good action.
In plain words

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 numbers

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.

Pick the output head

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.

Say it aloud

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.

π(a | s)
pi of a given s the chance of the whole action vector a.
p(a1 | s)
p of a-one given s the chance of the bin for dimension 1, such as steering.
p(a2 | s, a1)
p of a-two given s and a-one the chance of dimension 2's bin, after the policy picks dimension 1.
p(aD | s, a1..D−1)
p of a-D given everything before the last of the D dimensions.
In plain words

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 numbers

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 headTwo clumps?Catch
One number (squared error)No: predicts the meanThe averaging trap
One GaussianNo: one peakPeak at the mean, wide spread
Mixture of K GaussiansYes, up to KYou choose K in advance
Bins, one dimension at a timeYesBin width limits precision
Diffusion or flowYes, any numberMany 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.

Why does a two-bell mixture avoid the box when one Gaussian does not?

Chapter 7

Diffusion and Flow Policies

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.

Say it aloud

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.

L(θ)
L of theta the flow matching loss for weights θ.
Et, x0, (s,a)
the average over t, x-zero and pairs draw a time, a noise sample and a demo pair, many times.
vθ(xt, s, t)
v-theta of x-t, s, t the network's guess of the velocity at the mixed point x-t.
a − x0
a minus x-zero the true velocity of the straight line from the noise to the expert's action.
In plain words

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.

With numbers

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:

x ← x + (1/K) · vθ(x, s, t)

Flow noise into actions

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.

Why does a one-step flow sample land on the mean action?

Chapter 8

Action Chunking

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:

Choose the chunk size

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.

A 50 Hz robot runs chunks of k = 16. A push lands right after a prediction. At most how long until the next prediction can respond?

Chapter 9

Imitation Plus Reward

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.

PropertyImitationRL
Needs a rewardNoYes
Needs demosYesNo
Can beat the expertNoYes
Data neededLittle: supervisedMuch: must explore

Four common ways to join them:

  1. Clone, then fine-tune with RL. Cloning gives a sensible start; RL improves it (policy gradients).
  2. Weight the demos by their return. Copy good demos more. The device below does this.
  3. Learn the reward from the demos. GAIL (Ho and Ermon, 2016) trains a classifier to tell expert from policy and uses it as the reward.
  4. Language models. Pretraining clones text, fine-tuning clones curated answers, and RL from human feedback then optimises a learned reward.

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.

Say it aloud

W-i equals e to the power R-i over beta.

wi
w-i the weight of demo i's pairs in the cloning loss.
exp
e to the power makes every weight positive and stretches the gaps.
Ri
R-i the return of demo i.
β
beta the temperature: large copies all demos alike, small copies only the best.
In plain words

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 numbers

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.

Weight the demos by their return

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.

2.0

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.

You lower beta toward zero in return-weighted cloning. What happens?

Chapter 10

The Field Guide

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.

Terms

TermMeaning
Behaviour cloning (BC)Supervised learning from states to the expert's actions
Distribution shiftTest states differ from training states, because the policy's mistakes pick them
DAggerThe clone drives, the expert labels the visited states, retrain on everything
HG-DAggerThe expert takes over when needed; takeovers become data
Averaging trapSquared error predicts the mean of several good actions
Mixture of GaussiansK weighted bell curves: one peak per good action
Flow policyMoves noise into an action along a learned velocity
Action chunkThe next k actions, predicted at once and run open loop

The numbers from this page

WhatNumberWhy it matters
Cloning bound, ε = 0.01, T = 50at most 25 extraGrows with T squared
DAgger bound, ε = 0.01, T = 100, u = 2at most 2 extraGrows with T
Mean of −20, −18, −21, +22, +19−3.6°Into the box
Bins for 7 joints × 2561,792 outputs, not 7.2 × 1016Predict one dimension at a time
Chunk k = 8 at 50 Hz160 ms per predictionTime for 10 flow steps
Return-weighted clone, β = 27.83 against 5.67A reward lets you copy the best

Before you trust a cloned policy

The core code

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

Keep going

The takeaway. Copying is easy; staying on the data is hard. Collect labels where your policy goes, and give it an output that can hold more than one good answer.
A cloned robot works on 10-step tasks and fails on 100-step tasks. Its held-out error is low. What is the best next step?

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.

Credit and source

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.

CS 224R: Imitation Learning
The course site · DAgger · Diffusion Policy · Back to Gleams