Simple Algorithm
Reinforcement Learning · Bootstrapping · 22 min

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 ϵ\epsilon becomes an excess cost of order ϵT2\epsilon T^2 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 πE\pi^E produces demonstrations: trajectories (S0,A0,S1,A1,… )(S_0, A_0, S_1, A_1, \dots), from which we keep the state–action pairs as a dataset D={(si,ai)}i=1n\data = \{(s_i, a_i)\}_{i=1}^n. Behavior cloning (BC) fits a parameterized policy to them by maximum likelihood:

θ^∈arg max⁡θ ∑i=1nlog⁡πθ(ai∣si)\hat{\boldsymbol\theta} \in \argmax_{\boldsymbol\theta}\ \sum_{i=1}^{n}\log\pi_{\boldsymbol\theta}(a_i\mid s_i)
For discrete actions this is classification with the cross-entropy loss. For a Gaussian policy with a fixed variance it is least-squares regression of actions on states.
DerivationWhat the objective measures
  1. 1n∑i=1nlog⁡πθ(ai∣si) ⟶ Es∼dπE Ea∼πE(⋅∣s)[log⁡πθ(a∣s)]\frac1n\sum_{i=1}^n\log\pi_{\boldsymbol\theta}(a_i\mid s_i)\ \longrightarrow\ \E_{s\sim d^{\pi^E}}\ \E_{a\sim\pi^E(\cdot\mid s)}\big[\log\pi_{\boldsymbol\theta}(a\mid s)\big]

    With many samples, the average log-likelihood approaches its expectation under the expert's state distribution dπEd^{\pi^E} (the states the expert visits) and the expert's action choices:

  2. =− Es∼dπE[DKL(πE(⋅∣s) ∥ πθ(⋅∣s))] − Es∼dπE[H(πE(⋅∣s))]= -\,\E_{s\sim d^{\pi^E}}\Big[\KL\big(\pi^E(\cdot\mid s)\,\big\|\,\pi_{\boldsymbol\theta}(\cdot\mid s)\big)\Big]\ -\ \E_{s\sim d^{\pi^E}}\Big[\mathcal H\big(\pi^E(\cdot\mid s)\big)\Big]

    Add and subtract log⁡πE(a∣s)\log\pi^E(a\mid s) inside the inner expectation. The inner sum splits into a KL divergence and the expert's entropy, which does not depend on θ\boldsymbol\theta:

  3. 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 πθ\pi_{\boldsymbol\theta} itself would visit. That single fact drives the rest of the lesson.

python
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 policy

Behavior 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 TT steps, the cost of a step is C(s,a)∈[0,1]C(s,a)\in[0,1] (for example, 1 whenever the car is off the road), and J(π)=∑t=1TE[C(St,At)]J(\pi) = \sum_{t=1}^{T}\E\big[C(S_t, A_t)\big] is the expected total cost of π\pi, so lower is better. Let dπtd^t_\pi be the distribution of StS_t under π\pi and dπ=1T∑tdπtd_\pi = \frac1T\sum_t d^t_\pi its average. The expert is deterministic, and supervised learning controls the learner's error rate on the expert's states:

ϵ=Es∼dπE[Pr⁡a∼π(⋅∣s)(a≠πE(s))].\epsilon = \E_{s\sim d_{\pi^E}}\Big[\Pr_{a\sim\pi(\cdot\mid s)}\big(a\neq\pi^E(s)\big)\Big].

But J(π)J(\pi) is an expectation over dπd_\pi, 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.

DerivationWhere the square comes from: the tight example
  1. 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 pp, and set the expert's own cost to 0.

  2. ϵ=pT\epsilon = \frac{p}{T}

    The learner errs at only one of the TT steps of the expert's trajectory, so its average error on the expert's distribution is

  3. J(π)−J(πE)=p T=(ϵT) T=ϵ T2J(\pi) - J(\pi^E) = p\,T = (\epsilon T)\,T = \epsilon\,T^2

    With probability pp it spends all TT steps in the trap:

  4. Errors spread evenly along the path give the same order. With error ϵ\epsilon at every step on the path and the same trap, the agent is trapped at step tt with probability 1−(1−ϵ)t1-(1-\epsilon)^t, and the expected number of costly steps is ∑t=1T(1−(1−ϵ)t)≈ϵT2/2\sum_{t=1}^T\big(1-(1-\epsilon)^t\big)\approx\epsilon T^2/2 while ϵT≪1\epsilon T\ll1.

Predict before you look

In the tight example, take T=50T = 50 steps and a learner that errs at the first step with probability p=0.1p = 0.1. Its error rate on the expert's distribution is only ϵ=0.002\epsilon = 0.002. 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 0.1×50=50.1\times50 = 5, exactly T2ϵ=2500×0.002T^2\epsilon = 2500\times0.002. A supervised-learning intuition, which charges each step its own error, would predict Tϵ=0.1T\epsilon = 0.1: fifty times too optimistic.

DAgger: train where you will go

The fix is to train on dπd_\pi instead of dπEd_{\pi^E}. That is a chicken-and-egg problem, since dπd_\pi 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.

text
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 episodes

With β1=1\beta_1 = 1 the first round is plain behavior cloning on the expert's own trajectories. The simplest version then sets βi=0\beta_i = 0, and Ross et al. found that it often works best.

Read the bound carefully. It is linear in TT when the task is recoverable, meaning that the expert undoes a single mistake within a few steps (u=O(1)u = \order{1}), as in driving at moderate speed. If one wrong action can be fatal, uu is of order TT and the bound is quadratic again. And ϵN\epsilon_N is the best error achievable in the policy class on the learner's own states: if no policy in Π\Pi can imitate the expert there, more iterations do not help.

Check your understanding

Why does DAgger retrain on the aggregate of all the data collected so far, instead of only on the newest round?

  1. Because the newest round is labeled less reliably by the expert
  2. 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
  3. Because more data always lowers the error on any distribution
  4. 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.

RemedyWhat it addsWhat it needsExample
Recovery augmentationSynthetic off-path observations, labeled with a corrective actionA way to synthesize observations and a rule for the correctionALVINN; NVIDIA's side cameras and warped views
Noise injectionReal expert recoveries from perturbed statesAn expert who keeps demonstrating while noise perturbs its actionsDART (Laskey et al., 2017)
Human-gated interventionExpert corrections exactly where the learner gets into troubleA human who watches the learner and takes over when neededHG-DAgger (Kelly et al., 2019)
Interactive labelingExpert labels on all of the learner's statesAn expert who can label any stateDAgger
Action chunkingFewer decisions per episodeA policy that predicts the next kk actions at onceACT (Zhao et al., 2023)
The first three and the fourth all move the training distribution toward the states the learner reaches; chunking instead shortens the horizon over which errors compound.

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 NN expert trajectories and per-step rewards in [0,1][0,1], 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 ∣S∣H2log⁡N/N\abs{\mathcal S}H^2\log N/N in expectation, and that no algorithm can do better than order ∣S∣H2/N\abs{\mathcal S}H^2/N 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 ∣S∣H3/2/N\abs{\mathcal S}H^{3/2}/N.
  • 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 πθ\pi_{\boldsymbol\theta} to expert state–action pairs by maximum likelihood, which minimizes Es∼dπE[DKL(πE(⋅∣s) ∥ πθ(⋅∣s))]\E_{s\sim d^{\pi^E}}\big[\KL(\pi^E(\cdot\mid s)\,\|\,\pi_{\boldsymbol\theta}(\cdot\mid s))\big] on the expert's states, not on the learner's.
  • Covariate shift makes errors compound: an error rate ϵ\epsilon on the expert's distribution can cost up to T2ϵT^2\epsilon over TT 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 J(πE)+uTϵN+O(1)J(\pi^E) + uT\epsilon_N + \order{1}, linear in TT 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.

Question 1

In the large-data limit, maximizing ∑ilog⁡πθ(ai∣si)\sum_i\log\pi_{\boldsymbol\theta}(a_i\mid s_i) over expert pairs is equivalent to minimizing which quantity?

  1. Es∼dπθ[DKL(πE(⋅∣s) ∥ πθ(⋅∣s))]\E_{s\sim d^{\pi_{\boldsymbol\theta}}}\big[\KL(\pi^E(\cdot\mid s)\,\|\,\pi_{\boldsymbol\theta}(\cdot\mid s))\big], averaged over the learner's own states
  2. The KL divergence between the learner's and the expert's state distributions
  3. Es∼dπE[DKL(πE(⋅∣s) ∥ πθ(⋅∣s))]\E_{s\sim d^{\pi^E}}\big[\KL(\pi^E(\cdot\mid s)\,\|\,\pi_{\boldsymbol\theta}(\cdot\mid s))\big], averaged over the expert's states
  4. The learner's expected total cost
Show the answer

C. Es∼dπE[DKL(πE(⋅∣s) ∥ πθ(⋅∣s))]\E_{s\sim d^{\pi^E}}\big[\KL(\pi^E(\cdot\mid s)\,\|\,\pi_{\boldsymbol\theta}(\cdot\mid s))\big], 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.

Question 2

A cloned policy errs with probability ϵ=0.001\epsilon = 0.001 on the expert's state distribution in a task of T=100T = 100 steps with costs in [0,1][0,1]. What does the Ross–Bagnell bound guarantee about its extra cost over the expert?

  1. At most Tϵ=0.1T\epsilon = 0.1
  2. At most ϵ=0.001\epsilon = 0.001
  3. At most T2ϵ=10T^2\epsilon = 10, and some task attains it
  4. Nothing, because the error was measured on the wrong distribution
Show the answer

C. At most T2ϵ=10T^2\epsilon = 10, and some task attains it

T2ϵ=104×10−3=10T^2\epsilon = 10^4\times10^{-3} = 10, 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.

Question 3

DAgger guarantees J(π^)≤J(πE)+uTϵN+O(1)J(\hat\pi)\le J(\pi^E) + uT\epsilon_N + \order{1}. In which task is this no better than behavior cloning's quadratic bound?

  1. Driving at moderate speed, where the expert corrects a small swerve within a few steps
  2. A task where one wrong action traps the agent for the rest of the episode
  3. A short task with T=5T = 5
  4. 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 uu is of order TT, and uTϵNuT\epsilon_N is of order T2ϵNT^2\epsilon_N. Interaction helps exactly when the expert can recover.

Question 4

In which situation is plain behavior cloning most likely to be enough?

  1. A long task where one error is fatal, demonstrated by a near-perfect expert who never makes mistakes
  2. A task whose demonstrators pass obstacles on either side, learned with a single-Gaussian policy
  3. A handful of demonstrations of a long, precise task
  4. 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

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