Imitation Learning
Behavior cloning, compounding errors and DAgger.
Record an expert, fit a policy by supervised learning, deploy: behavior cloning is the most common way to give a robot or a car a skill. This lesson builds it, shows exactly why it degrades on long tasks, derives DAgger from the observation that a learner must be trained where it actually goes, and collects the cheaper tricks that make plain cloning work surprisingly often.
What you’ll learn
- Formulate behavior cloning as maximum likelihood on expert state–action pairs, and show that it minimizes a forward KL divergence on the expert's state distribution.
- Explain covariate shift, and compute how a per-step error rate becomes an excess cost of order in the worst case.
- Write DAgger, explain its reduction to no-regret online learning, and state its guarantee with its assumptions: a queryable expert and recoverability.
- Compare the practical remedies (recovery augmentation, noise injection, human-gated interventions, action chunking) and judge when behavior cloning alone is enough.
Imitation as supervised learning
An expert policy produces demonstrations: trajectories , from which we keep the state–action pairs as a dataset . Behavior cloning (BC) fits a parameterized policy to them by maximum likelihood:
With many samples, the average log-likelihood approaches its expectation under the expert's state distribution (the states the expert visits) and the expert's action choices:
Add and subtract inside the inner expectation. The inner sum splits into a KL divergence and the expert's entropy, which does not depend on :
So behavior cloning minimizes the forward KL from the expert's action distribution to the policy's, averaged over the states the expert visits. Nothing in the objective refers to the states that itself would visit. That single fact drives the rest of the lesson.
import torch
import torch.nn as nn
import torch.nn.functional as F
def behavior_cloning(states, actions, epochs=50, batch=256, lr=1e-3):
"""states: (N, ds) and actions: (N, da) float tensors from expert demonstrations."""
policy = nn.Sequential(nn.Linear(states.shape[1], 256), nn.ReLU(),
nn.Linear(256, 256), nn.ReLU(),
nn.Linear(256, actions.shape[1]))
opt = torch.optim.Adam(policy.parameters(), lr=lr)
for _ in range(epochs):
perm = torch.randperm(len(states))
for i in range(0, len(states), batch):
idx = perm[i:i + batch]
loss = F.mse_loss(policy(states[idx]), actions[idx]) # fixed-variance Gaussian
opt.zero_grad()
loss.backward()
opt.step()
return policyBehavior cloning for continuous actions with a deterministic (fixed-variance Gaussian) policy. Every training state comes from the expert's trajectories; the loss never sees what happens when the policy drives.
Covariate shift and compounding errors
To see the obstacle precisely, follow the imitation literature and measure performance by a cost. A task lasts steps, the cost of a step is (for example, 1 whenever the car is off the road), and is the expected total cost of , so lower is better. Let be the distribution of under and its average. The expert is deterministic, and supervised learning controls the learner's error rate on the expert's states:
But is an expectation over , the states the learner reaches. A model trained on one input distribution and tested on another suffers covariate shift, and here the learner's own mistakes create the shift.
The expert follows a path. One wrong action at the first step drops the agent into a trap state it never leaves, where every step costs 1; elsewhere on the path the learner agrees with the expert. Let the learner err at the first step with probability , and set the expert's own cost to 0.
The learner errs at only one of the steps of the expert's trajectory, so its average error on the expert's distribution is
With probability it spends all steps in the trap:
Errors spread evenly along the path give the same order. With error at every step on the path and the same trap, the agent is trapped at step with probability , and the expected number of costly steps is while .
In the tight example, take steps and a learner that errs at the first step with probability . Its error rate on the expert's distribution is only . What is its expected extra cost over the expert?
Show the answer
5
With probability 0.1 the learner is trapped for all 50 steps, so the extra cost is , exactly . A supervised-learning intuition, which charges each step its own error, would predict : fifty times too optimistic.
DAgger: train where you will go
The fix is to train on instead of . That is a chicken-and-egg problem, since depends on the policy being trained. DAgger (dataset aggregation; Ross, Gordon & Bagnell, 2011) breaks it by iterating: roll out the current policy, have the expert label the states it visited, add them to everything collected so far, and retrain.
DAgger(expert πE, policy class Π, iterations N, mixing weights β1, ..., βN)
D ← ∅; π̂1 ← any policy in Π
for i = 1, ..., N:
πi ← βi·πE + (1 − βi)·π̂i # at each step, follow the expert with prob. βi
roll out πi for m episodes and record every visited state s
Di ← {(s, πE(s))} # the expert labels the states πi reached
D ← D ∪ Di # aggregate: keep all earlier data
π̂(i+1) ← argmin over π in Π of the total loss of π on D
return the best π̂i on validation episodesWith the first round is plain behavior cloning on the expert's own trajectories. The simplest version then sets , and Ross et al. found that it often works best.
Read the bound carefully. It is linear in when the task is recoverable, meaning that the expert undoes a single mistake within a few steps (), as in driving at moderate speed. If one wrong action can be fatal, is of order and the bound is quadratic again. And is the best error achievable in the policy class on the learner's own states: if no policy in can imitate the expert there, more iterations do not help.
Why does DAgger retrain on the aggregate of all the data collected so far, instead of only on the newest round?
- Because the newest round is labeled less reliably by the expert
- Because training on everything is follow-the-leader, a no-regret strategy: the policy must do well on every state distribution seen so far, which stops it from fixing new states while forgetting old ones
- Because more data always lowers the error on any distribution
- Because the newest round contains only states the expert already demonstrated
Show the answer
B. Because training on everything is follow-the-leader, a no-regret strategy: the policy must do well on every state distribution seen so far, which stops it from fixing new states while forgetting old ones
Training only on the newest round chases a moving target: a policy fixed for today's states visits different states tomorrow and may forget yesterday's lesson, and the iterates can oscillate. Minimizing the total loss over all rounds is follow-the-leader, whose regret guarantee is what turns DAgger into a bound on the learner's performance under its own distribution.
Cheaper ways to put recoveries into the data
DAgger's guarantee has a price: an expert on call who can label any state, including the strange ones an early policy reaches, and several rounds of rollouts by a policy that may be unsafe. Human experts also find it hard to label recorded states after the fact, because the right action depends on feel and timing that a frozen frame does not convey. Several cheaper remedies attack the same covariate shift.
| Remedy | What it adds | What it needs | Example |
|---|---|---|---|
| Recovery augmentation | Synthetic off-path observations, labeled with a corrective action | A way to synthesize observations and a rule for the correction | ALVINN; NVIDIA's side cameras and warped views |
| Noise injection | Real expert recoveries from perturbed states | An expert who keeps demonstrating while noise perturbs its actions | DART (Laskey et al., 2017) |
| Human-gated intervention | Expert corrections exactly where the learner gets into trouble | A human who watches the learner and takes over when needed | HG-DAgger (Kelly et al., 2019) |
| Interactive labeling | Expert labels on all of the learner's states | An expert who can label any state | DAgger |
| Action chunking | Fewer decisions per episode | A policy that predicts the next actions at once | ACT (Zhao et al., 2023) |
Two further failure modes are worth knowing. Giving the policy more history, such as several past frames, can hurt: it may latch onto cues that merely accompany the expert's action, like a dashboard light that turns on whenever the brakes are applied, which de Haan, Jayaraman and Levine (2019) called causal confusion. And when demonstrators solve the same situation in different ways, mean-regression cloning averages them into an action nobody took; that is the subject of the Fixed Point lesson Expressive Policies: Diffusion Policy & Action Chunking.
When is behavior cloning enough?
The quadratic bound is a worst case, and two lines of recent theory sharpen what it means.
- Interaction cannot beat the worst case. In tabular episodic MDPs with expert trajectories and per-step rewards in , Rajaraman, Yang, Jiao and Ramchandran (2020) showed that the policy which mimics the expert wherever the expert was observed is suboptimal by at most order in expectation, and that no algorithm can do better than order in the worst case, even one allowed to query the expert at the states it visits. Knowing the transition model lowers the achievable rate to order .
- The loss matters. Foster, Block and Misra (2024) analyzed cloning with the logarithmic loss for general policy classes that contain the expert's policy and found a much milder dependence on the horizon than the classical analysis suggests: for deterministic stationary policies, linear in the horizon under dense rewards. They also showed that, without further assumptions on the policy class, online interaction cannot improve on offline cloning with the log loss in the worst case.
Together with DAgger's bound, the picture is this: interaction pays off in recoverable problems, where the expert's corrections are informative; in unrecoverable ones nothing escapes the quadratic rate; and with plentiful, diverse data, plain cloning is often competitive. If the data also record rewards and mix good and bad behavior, offline RL can do better than copying, a trade-off taken up in Offline RL.
Key takeaways
- Behavior cloning fits to expert state–action pairs by maximum likelihood, which minimizes on the expert's states, not on the learner's.
- Covariate shift makes errors compound: an error rate on the expert's distribution can cost up to over steps, and that bound is tight.
- DAgger trains on the states the learner visits, labeled by the expert. As no-regret online learning it guarantees , linear in when the expert recovers from single mistakes.
- Interaction is costly. Recovery augmentation, noise injection in demonstrations (DART), human-gated interventions and action chunking are cheaper ways to put recoveries into the data or to shorten the horizon.
- The quadratic rate is a worst case: no method escapes it in unrecoverable problems, and with large, diverse data plain cloning often works well.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
In the large-data limit, maximizing over expert pairs is equivalent to minimizing which quantity?
- , averaged over the learner's own states
- The KL divergence between the learner's and the expert's state distributions
- , averaged over the expert's states
- The learner's expected total cost
Show the answer
C. , averaged over the expert's states
The log-likelihood averages over the states in the data, which are the expert's. It differs from the expected forward KL only by the expert's entropy, a constant. That is exactly why cloning can look excellent on held-out expert data and still fail when it drives.
A cloned policy errs with probability on the expert's state distribution in a task of steps with costs in . What does the Ross–Bagnell bound guarantee about its extra cost over the expert?
- At most
- At most
- At most , and some task attains it
- Nothing, because the error was measured on the wrong distribution
Show the answer
C. At most , and some task attains it
, out of a worst possible 100. The error measured on the expert's distribution does give a guarantee, but a weak one, and the tight example shows that it cannot be improved without further assumptions.
DAgger guarantees . In which task is this no better than behavior cloning's quadratic bound?
- Driving at moderate speed, where the expert corrects a small swerve within a few steps
- A task where one wrong action traps the agent for the rest of the episode
- A short task with
- A task in which the policy class contains the expert's policy
Show the answer
B. A task where one wrong action traps the agent for the rest of the episode
If a single mistake costs up to the rest of the episode, the recoverability constant is of order , and is of order . Interaction helps exactly when the expert can recover.
In which situation is plain behavior cloning most likely to be enough?
- A long task where one error is fatal, demonstrated by a near-perfect expert who never makes mistakes
- A task whose demonstrators pass obstacles on either side, learned with a single-Gaussian policy
- A handful of demonstrations of a long, precise task
- Large and diverse demonstrations that include recoveries, of a task in which small errors die out quickly
Show the answer
D. Large and diverse demonstrations that include recoveries, of a task in which small errors die out quickly
Cloning fails when the learner reaches states the data do not cover and cannot get back. Diverse data with recoveries cover those states, and quickly decaying errors keep the learner near the data. That is the regime in which large-scale cloning works well.
Go deeper
- Compounding Errors & Interactive Imitation · Why cloning errors can grow quadratically with the horizon, and how DAgger makes them linear.
- Adversarial Imitation: GAIL & Distribution Matching · Imitation as matching occupancy measures, with a discriminator as the reward.
- Expressive Policies: Diffusion Policy & Action Chunking · Multimodal demonstrations, and the policy classes that can represent them.
Further reading
- D. A. Pomerleau, "ALVINN: An autonomous land vehicle in a neural network," Advances in Neural Information Processing Systems 1 (1989).
- S. Ross, G. J. Gordon & J. A. Bagnell, "A reduction of imitation learning and structured prediction to no-regret online learning," AISTATS (2011).
- M. Bojarski et al., "End to end learning for self-driving cars," arXiv:1604.07316 (2016).
- M. Laskey, J. Lee, R. Fox, A. Dragan & K. Goldberg, "DART: Noise injection for robust imitation learning," CoRL (2017).