Introduction to Robot Learning · Lecture 6 of 25 · CMU 16-831

Imitation Learning, Part 2: DAgger, GAIL & Diffusion Policy

Behavior cloning drifts off the road and the cost compounds. Three ideas fix it: put the expert back in the loop, match whole distributions instead of single steps, and learn to copy demonstrations that branch.

Prerequisites: behavior cloning & compounding error (Lecture 5) + a little Python. No GANs or diffusion assumed — we build them from zero.
10
Chapters
6
Simulations
3
Code Labs

Chapter 0: The Slip That Snowballs

Last lecture we taught a robot to drive by behavior cloning (BC): record an expert, then train a policy to copy the expert's action at every state, exactly like a supervised classifier. On the states the expert visited, the clone is good. And yet on the open road it veers off and crashes. Why?

Here is the villain again, in one sentence. The first time the clone picks a slightly wrong action, it lands in a state the expert never visited — a little too close to the curb. Nothing in the training data says how to recover from there, because the expert was never there. So the clone makes another mistake, drifts further into unseen territory, and snowballs. This is distribution shift (also called covariate shift): the states the policy actually visits at test time stop matching the states it was trained on.

The number that should scare you. If the clone errs with probability ε per step over a horizon of H steps, a supervised-learning intuition predicts ε·H total mistakes. Ross and Bagnell proved the truth is far worse: up to ε·H². Double the episode length and you quadruple the trouble. The cost is quadratic in the horizon, not linear, precisely because a single slip pushes you off-distribution for the rest of the episode.

So the question for this whole lecture is blunt: how do we fix imitation learning so the error stops compounding? Today gives three answers, each a different philosophy.

Watch the cloned policy leave the road — and watch DAgger stay on it

The teal band is where the expert demonstrated. Behavior cloning is fine until its first slip, then it spirals through states it never saw. Toggle DAgger on: the expert has labeled those recovery states, so the policy steers back. Raise the per-step error and run again.

Per-step error ε 0.060
Ready.
A behavior-cloned policy errs only 4% of the time on the expert's states, yet crashes on the road. What is the core reason?

Chapter 1: DAgger — Put the Expert Back in the Loop

Behavior cloning has one fatal asymmetry. It trains on the expert's states but is tested on the learner's states — and those two sets diverge the moment the learner slips. DAgger (Dataset Aggregation, Ross, Gordon & Bagnell, 2011) fixes the asymmetry head-on: collect training data from the states the learner actually visits, and have the expert say what it would have done there.

The trick is one short loop. Read it slowly — every method today is a variation on putting the right data in front of the policy.

0 · Seed
Start with the expert's demonstrations as your dataset D. Train a first policy π₁ by behavior cloning on D.
↓ now do something BC never does
1 · Roll out the learner
Drive the world with the current policy π. It will drift into states the expert never showed — that's the point. Record the observations it visits.
↓ the key step
2 · Expert relabels
For each visited observation o, ask the expert: "what action would you take here?" Get the label a* = π*(o). The learner moved; the expert annotates.
↓ the "aggregate" in Dataset Aggregation
3 · Aggregate
Append these new (o, a*) pairs to D. Keep the old data too — D only ever grows. D ← D ∪ {(o, a*)}.
↓ ordinary supervised learning
4 · Retrain
Train a fresh policy on all of D by behavior cloning. Set π to it. Go back to step 1.
↻ repeat for a handful of iterations

Notice what each actor does. The learner generates the states (it decides where the trajectory goes); the expert generates the labels (it decides the correct action there). That division of labor is the whole idea. BC let the expert pick both the states and the labels — which is exactly why the learner's states went unseen.

The one-line mental model. BC trains on "where the expert goes." DAgger trains on "where the learner goes, labeled by the expert." After a couple of iterations the dataset is dense exactly in the off-road, near-the-curb states where recovery matters — the states BC never had.

The data flow, concretely

Picture a 100-step drive. Iteration 1's policy slips at step 20 and ends up hugging the curb for steps 20–100. DAgger feeds all 80 of those curb-states to the expert, who labels each with "steer left, hard." Those 80 labeled pairs join D. Iteration 2's policy, trained on D, now knows how to steer back from the curb — so it slips less, and the states it visits look more and more like the expert's. The training distribution and the test distribution converge. That convergence is the cure for compounding error, and we make it precise next chapter.

The cost DAgger pays. It needs an interactive, queryable expert — one you can put in any state and ask "what now?" A human who can only drive whole trips, not answer "what would you do here?", is awkward to DAgger. That practical limitation is exactly why later chapters reach for privileged teachers (a queryable white-box expert) and for GAIL (no expert queries at all).

In one DAgger iteration, who decides which states end up in the new training data, and who decides the action labels for them?

Chapter 2: Why DAgger Beats the Quadratic

BC's cost grows like ε·H². DAgger's grows like ε·H — linear. That single change of exponent is the entire payoff, so let us see why it happens, with no heavy math.

The quadratic in BC came from a mismatch: the policy was trained on the expert's state distribution but evaluated on its own. The bound has a worst-case factor that scales with the horizon because once you're off-distribution you can stay lost for the rest of the episode. DAgger removes the mismatch by training on its own induced distribution of states — the very thing it is evaluated on. When the training distribution equals the test distribution, there is no covariate shift left to amplify, and the cost collapses back to linear.

The formal statement (intuition only). DAgger is a no-regret online learning algorithm. Across its iterations the aggregated dataset comes to represent the states the final policy visits, so the average training loss ε the policy achieves on its own distribution translates into a total cost that grows like ε·H, not ε·H². The "stay-lost" multiplier is gone because the policy has been trained on how to not stay lost.

See the gap open up

The simulation below races the two bounds as you stretch the horizon. BC's curve bends upward (quadratic); DAgger's stays a straight line (linear). At short horizons they're close. Stretch H and the gap explodes — which is exactly the regime real robots live in, where an episode is hundreds or thousands of control steps.

BC's quadratic vs. DAgger's linear cost

Both policies err with the same per-step rate ε. The warm curve is behavior cloning (stays lost after a slip → cost ~ε·H²); the teal line is DAgger (recovers → cost ~ε·H). Slide ε and the horizon to watch the gap.

Per-step error ε 0.050
Max horizon H 200

Now let's measure the DAgger improvement ourselves instead of trusting the curve. The lab simulates DAgger iterations: each iteration rolls out the current policy, the expert relabels the visited states, and we retrain. As recovery data accumulates, the policy's drift on a held-out test rollout should fall — far below the BC baseline. Your one line is the aggregation step that makes the data grow.

Why does DAgger's trajectory cost grow only linearly in the horizon H, while behavior cloning's grows quadratically?

Chapter 3: When One Answer Isn't Enough — Multimodal Demos

DAgger fixes where the data comes from. But there is a second, sneakier failure of behavior cloning that more data alone cannot fix — and the lecture spends real time on it, because solving it is what motivates GAIL and Diffusion Policy.

Human demonstrators are multimodal: faced with the same scene, they don't always do the same thing. Two drivers reach a rock in the road; one swerves left, one swerves right. Both are perfect demonstrations. Now train a regression policy — a network that outputs a single action and is fit by mean-squared error to copy the demos. What does it learn at the rock?

The averaging trap. Minimizing mean-squared error to "go left" and "go right" gives you their mean: go straight — directly into the rock. A unimodal regression policy cannot represent "left OR right"; it can only represent the average, and the average is the one action both demonstrators avoided. More data makes the average sharper, not better.

This is why the lecture says behavior cloning needs powerful models, not just more data. The instructor lists two upgrades that go beyond a plain feed-forward regressor:

Two good demos, one rock — why the mean crashes

The expert demonstrated swerving left and swerving right around the obstacle — both valid. The regression (mean) policy averages them and drives straight into the rock. Toggle to a multimodal policy: it samples one mode and goes around. Press Run to send a car down each.

Ready.

Let's nail the failure in code so it isn't hand-waving. The lab fits a single mean to a bimodal set of demonstrated actions and measures how badly the mean misses — then compares it to a policy that picks the nearest mode.

Two experts swerve left and right around a rock. A mean-squared-error regression policy is trained on both. What does it output at the rock, and why?

Chapter 4: Privileged Teachers — A Better Expert to Imitate

Before the generative models, the lecture offers a clever detour. Sometimes the hard part isn't where the data comes from — it's that learning directly from raw sensors is brutally hard because the observation is high-dimensional (camera pixels, lidar). The idea: don't imitate a human; imitate a machine that knows more than the final robot ever will.

This is the privileged teacher (or teacher–student) recipe, and it comes in two stages:

Stage 1 · Train the privileged teacher
Give a "teacher" policy access to ground-truth state the real robot won't have: exact object poses, terrain contact, traffic-light state, the wind. Train it (often by RL, sometimes from an expert). It learns a great policy because its input is easy.
↓ the teacher becomes a queryable, white-box expert
Stage 2 · Distill into the student
Train a sensorimotor student that sees only what the real robot sees (raw pixels, proprioceptive history) to imitate the teacher's actions — often with DAgger, since the teacher can be queried in any state.
Why this is so much easier than direct imitation. The teacher is a white box you control — so you can run DAgger against it for free (no human in the loop), generate unlimited supervision, and do heavy data augmentation. And because the teacher solved the task from clean state, the student only has to learn the perception half — mapping messy sensors to the action the teacher already figured out.

Three real systems

SystemTeacher sees (privileged)Student sees
Autonomous driving (CARLA)Ground-truth lane, traffic-light state, other vehicles' positions/velocitiesFront-camera pixels
Legged locomotion (RMA, in sim)Terrain, friction, contact forces, applied disturbancesProprioceptive history (IMU, joint angles)
Agile drone flightAn MPC controller that knows the full stateOnboard sensing

One subtlety the lecture flags: the student doesn't have to learn in the teacher's action space. In RMA (Rapid Motor Adaptation) the student predicts the teacher's compressed latent — an encoding of the privileged info — rather than raw actions, which is easier to regress from a history of proprioception. The principle stands: an easy-to-train teacher manufactures clean supervision for a hard-to-train student.

Teacher knows the wind; student must infer it

A robot must hold the center line under an unknown wind. The privileged teacher is handed the true wind and cancels it instantly. The student sees only its recent positions and must infer the wind from how it has been pushed — lagging at first, then catching up. Slide the wind and run.

Wind strength 0.80
Ready.
What makes the privileged-teacher recipe easier than directly imitating a human from raw pixels?

Chapter 5: GAIL — Imitation as Distribution Matching

DAgger and privileged teachers both lean on a queryable expert. GAIL (Generative Adversarial Imitation Learning, Ho & Ermon, 2016) throws that crutch away. The setting: you have a fixed batch of expert trajectories, you cannot query the expert for more, and you are not given any reward function. Just demonstrations. How do you learn a policy?

The shift in viewpoint is the whole lesson. BC matched the expert's action at each state, one timestep at a time — which is what made it fragile to compounding error. GAIL instead matches the distribution of state–action pairs the policy produces to the distribution the expert produces. If the two distributions are indistinguishable, the policy behaves like the expert — trajectory-wide, not just per-step.

The reframing. "Act like the expert" becomes "make your rollouts statistically indistinguishable from the expert's rollouts." This is distribution matching, and it borrows its engine straight from generative adversarial networks: a discriminator that tries to tell the two distributions apart, and a policy (the generator) that tries to fool it.

The discriminator: inputs and outputs

The discriminator D is a classifier. It takes a single state–action pair (s, a) — the data point GAIL works with is the pair, written z = (s, a) on the slides — and outputs one number in [0, 1]: its estimate of the probability that this pair came from the expert rather than from the policy. Near 1 means "I think the expert did this"; near 0 means "I think the policy did this."

You train D by ordinary binary classification: feed it expert pairs labeled 1 and policy pairs labeled 0, and minimize cross-entropy. A good D learns a decision boundary that separates expert behavior from policy behavior in (state, action) space.

The discriminator's decision boundary — and the policy pushing across it

Each dot is a state–action pair. Teal = expert, warm = current policy. The shaded line is the discriminator's learned boundary (it scores everything to one side as "expert"). Press Train D to refit the boundary, then Policy step to nudge the policy's pairs toward the expert cluster — fooling D. Repeat: the two clusters merge.

Ready — policy and expert clusters are far apart.
Connection to inverse RL. The lecture frames GAIL as the efficient cousin of inverse reinforcement learning (IRL). Classic IRL recovers the expert's hidden cost function and then runs RL on it — two expensive nested loops. GAIL's discriminator plays the role of that cost function implicitly, so you skip the explicit cost-recovery step and learn the policy directly. Crucially, GAIL never needs the expert's reward — it manufactures its own learning signal from the discriminator.

In GAIL, what does the discriminator take as input and what does it output?

Chapter 6: GAIL — The Adversarial Loop

Now the data flow. GAIL repeats three steps until the discriminator can no longer tell expert from policy. The instructor's exact phrasing: sample from the student, update the discriminator to classify teacher vs. student, then train the student to minimize the discriminator's accuracy.

1 · Sample policy rollouts
Run the current policy π in the environment, collecting its (state, action) pairs. These are the "fake" samples.
↓ train the critic
2 · Update the discriminator D
Binary classification: expert pairs → label 1, policy pairs → label 0. D learns to output high on expert-like pairs, low on policy-like pairs.
↓ the gradient that trains the policy
3 · Update the policy π by RL
Define a reward from the discriminator — high when D is fooled into thinking the pair is expert. Run a policy-gradient RL step (e.g. TRPO/PPO) to maximize it. The policy learns to visit (state, action) pairs D believes are expert.
↻ repeat — D and π chase each other to a draw

Step 3 is the part that surprises people, so let's be precise about where the policy's gradient comes from. There is no expert reward and no per-step imitation label. Instead, GAIL hands the policy a synthetic reward built from the discriminator's score: a pair that D thinks is expert pays well; a pair D recognizes as policy pays poorly. The policy is then optimized by reinforcement learning on that synthetic reward — not by supervised regression to actions. That is the deep difference from BC and even DAgger.

The misconception to kill. "GAIL needs the expert's reward function." It does not. GAIL is for exactly the setting where no reward is given — only demonstrations. The discriminator invents the reward signal: fooling it pays. That self-manufactured reward is what lets a pure-RL policy optimizer imitate, without ever being told the task's true objective.

Why GAIL handles multimodal behavior — and the price

The lecture asks: can GAIL model multimodal behavior? Yes — like a GAN, the policy is a sampler from a distribution, so it can put mass on both "swerve left" and "swerve right" as long as both look expert to D. That is a genuine advantage over mean-regression BC. The price is adversarial training's notorious instability: the discriminator and policy are locked in a minimax game, and like GANs, GAIL can oscillate, collapse modes, or need careful tuning to converge. There is no free lunch — you trade BC's brittleness for an optimization that is harder to stabilize.

Let's build the reward signal itself: a tiny logistic discriminator that scores expert vs. policy samples, and the reward the policy would climb.

Where does the gradient that improves the GAIL policy come from?

Chapter 7: Diffusion Policy — Copying Demos That Branch

GAIL captures multimodal behavior but is hard to train. Is there a way to get the multimodality without the adversarial game? Yes — and it is the hottest idea in modern imitation learning: Diffusion Policy. It takes the diffusion model from Lecture 4 (the engine behind image generators) and points it at actions instead of pixels.

The recipe matches the multimodal upgrade from Chapter 3: replace the single-action output with a generative model of the action distribution. Diffusion is just an unusually good generative model, because it can represent sharp, multi-peaked distributions that a Gaussian or even a Gaussian mixture struggle with.

How a diffusion model generates an action

The two-process picture, stated for actions:

Forward (training only)
Take a real expert action sequence and gradually corrupt it by adding small random noise, step by step, until it's pure noise. Train a network to predict the noise that was added at each step.
↓ at run time, reverse it
Reverse (generation)
Start from pure random noise. Repeatedly subtract the network's predicted noise — denoising — conditioned on the current observation. After several denoising steps the noise has been sculpted into a clean, valid action sequence.
Why denoising captures both swerves and regression can't. Each generation starts from fresh random noise and is pulled downhill toward the nearest valley of "expert-like actions." Because the demos have two valleys — one for "left", one for "right" — some noise samples fall into the left valley and some into the right. The model commits to one mode per sample instead of averaging. A mean-squared-error regressor has a single output and is forced to sit on the ridge between the valleys; diffusion never does.

Two engineering choices the lecture and the Diffusion Policy paper stress. First, diffusion policies usually predict a short sequence (chunk) of future actions, not a single action — the same action chunking idea behind ACT (Action Chunking with Transformers, built on a conditional VAE). Predicting a chunk keeps the motion coherent and reduces the dithering that comes from re-deciding every single step. Second, the denoiser is conditioned on the observation, so the generated actions are appropriate to what the robot currently sees.

Denoising into a mode — many samples, two valleys

The curve is the demonstrated action distribution: two peaks (left swerve, right swerve). Press Sample to drop noisy candidate actions (warm) at random and watch them denoise — slide downhill into one peak or the other. The blue line is where mean-regression would put its single action: stuck in the dead valley between the peaks.

Ready.
Generative model + ILHow it represents the action distributionNote
Gaussian mixture (GMM)Predefined fixed number of Gaussian modesSimple; must guess the mode count
Conditional VAE (ACT)Latent variable decoded to an action chunkAction chunking + temporal ensemble
GAN (GAIL)Adversarial samplerMultimodal but unstable to train
Diffusion (Diffusion Policy)Iterative denoising of an action chunkSharp multimodality, stable training
Why can a diffusion policy represent "swerve left OR swerve right" while a mean-squared-error regressor cannot?

Chapter 8: Showcase — The Imitation Bench

Time to put all three fixes side by side on the same road. The car must drive a winding lane that splits around an obstacle (a multimodal demo) under per-step noise. You choose the method and watch what breaks and what survives.

Imitation bench — drive the split-lane under noise

Pick a method, set the per-step noise, and press Run. The teal band is the expert lane; it forks around the red obstacle. Watch BC drift and crash, DAgger recover but average into the rock, and the multimodal policy thread one fork cleanly.

Per-step noise 0.050
Pick a method, then Run.

The instructive sequence: run BC at noise 0.08 (it drifts and hits the rock), switch to DAgger (it stops drifting but still aims at the rock because it averages the fork), then Diffusion (it both stays on the lane and picks a fork). The three failures and fixes of this whole lecture, in one screen: drift → DAgger; averaging → generative; both at once → a modern diffusion policy.

The synthesis. The two diseases of behavior cloning are distribution shift (fixed by collecting the learner's states — DAgger, or a queryable privileged teacher) and mode averaging (fixed by a generative, multimodal policy — GAIL, VAE/ACT, or Diffusion Policy). Real systems often combine them: a diffusion policy distilled from a privileged teacher gets both cures at once.

Chapter 9: Connections & Cheat Sheet

You arrived with one broken algorithm — behavior cloning — and leave with three repairs and the judgment to choose between them. Here is the whole lecture on one card.

Cheat sheet — the vocabulary you now own.
  • The two diseases of BC = distribution shift (cost ~ ε·H²) and mode averaging (the mean of multimodal demos is an action nobody chose).
  • DAgger = roll out the learner → expert relabels visited states → aggregate into a growing dataset → retrain. Cures distribution shift; cost drops to ~ε·H. Needs a queryable expert.
  • Privileged teacher = train a teacher on ground-truth state (often by RL), then distill into a sensorimotor student (often via DAgger). The student learns perception; the teacher already learned control.
  • GAIL = imitation as distribution matching. A discriminator scores (s,a) pairs as expert-vs-policy; its score becomes a reward; the policy is trained by RL to fool it. No expert reward, no expert queries. Multimodal but adversarially unstable.
  • Diffusion Policy = generate an action chunk by denoising from noise, conditioned on the observation. Captures sharp multimodality, trains stably. Cousins: GMM, conditional VAE (ACT), GAN.
  • Use history = condition on a window of past observations, not just the current one — human demos aren't Markovian.

When to reach for which

SituationBest tool
You can query the expert in any stateDAgger (directly cures drift)
You have a simulator with ground-truth statePrivileged teacher → student distillation
Fixed demos, no expert access, no rewardGAIL (distribution matching)
Demos branch (multiple valid actions)Diffusion Policy / conditional VAE (ACT)
Demonstrators depend on recent historySequence model over an observation window

Where to go next on this site

This lesson is Lecture 6 of the CMU 16-831 series. Continue along the spine, and branch out to the companion Gleams that expand each thread:

The test of this lesson. Open the original Lecture 6 slides. You should be able to explain, from memory: why BC drifts and how DAgger's aggregate-and-retrain loop stops it; why the mean of multimodal demos crashes; what the GAIL discriminator inputs and outputs and where the policy's gradient comes from (and why no expert reward is needed); and how denoising lets a diffusion policy pick one mode instead of averaging. If you can, you're ready for Lecture 7.

"Don't train on where the expert went — train on where you went, labeled by the expert."