Learning from Demonstrations

Dive into Deep Learning · §14.5

Learning from Demonstrations
behavior cloning · covariate & distribution shift · quadratic compounding error · DAgger · supervised fine-tuning & distillation

Why an 82%-Accurate Clone Succeeds Only 66% of Runs

Motivation & Mental Model

  • Pomerleau’s ALVINN (1989): Because the human driver stayed centered, road-camera demonstrations contained no examples of recovering from the roadside.
  • Calm FrozenLake benchmark: A clone matching \pi^* with probability 0.818 on demonstrated states succeeds in only 66.0\% of episodes—whether trained on 3 expert episodes or 1{,}000.

Recording Expert Demonstrations on Calm Ice

Reduction to Supervised Classification

A demonstration is an expert trajectory (s_0, a_0^*, s_1, a_1^*, \ldots); behavior cloning discards rewards and dynamics, retaining only (s_i, a_i^*) pairs:

18 state-action pairs from 3 expert episodes, covering states [ 0  4  8  9 13 14]
  • Narrow state-space tube: On calm ice, every expert episode follows the exact same 6-cell trajectory [0, 4, 8, 9, 13, 14] (down, down, right, down, right, right), leaving frozen cells 1, 2, 3, 6, 10 completely unvisited.

The Differentiable Policy Container

Softmax Regression Over State-Action Preferences

Policy wraps a neural or tabular score model with an Adam optimizer and computes \log \pi_\theta(a \mid s) via log_softmax:

class Policy(nn.Module):
    def __init__(self, policy, lr=1e-2):
        super().__init__()
        self.policy = policy
        self.opt_pi = torch.optim.Adam(policy.parameters(), lr=lr)

    def log_prob(self, obs, act):
        return torch.log_softmax(self.policy(obs), dim=-1) \
                    .gather(-1, act[:, None]).squeeze(-1)
  • Tabular specialization (Policy.tabular): Uses a zero-initialized 16 \times 4 embedding table of preferences \theta_{s,a} so \pi_\theta(a \mid s) = \exp(\theta_{s,a}) / \sum_{a'} \exp(\theta_{s,a'}) starts uniformly at 1/4.

Weighted Log-Likelihood Ascent Step

The Shared Policy Optimization Primitive

Both behavior cloning and policy gradient methods (§14.7–§14.9) call policy_step to take one ascent step on \frac{1}{n}\sum_{i=1}^n w_i \log \pi_\theta(a_i \mid s_i):

def policy_step(ac, obs, act, weight):
    """One ascent step on (1/n) sum_t w_t log pi(a_t|s_t) over a batch of
    n states and actions; the weights w arrive as numpy, that is, as data."""
    w = torch.as_tensor(weight)
    loss = -(w * ac.log_prob(torch.as_tensor(obs),
                             torch.as_tensor(act))).mean()
    ac.opt_pi.zero_grad()
    loss.backward()
    ac.opt_pi.step()
    return loss.item()
  • Unit weights for cloning: Behavior cloning passes w_i = 1 for every demonstrated pair, minimizing standard multiclass cross-entropy loss.

Fitting the Clone to a Fixed Disagreement Rate

Controlling Training-Set Classification Error

To model imperfect real-world classifiers (limited capacity, feature aliasing, or noisy human labels), clone halts once average training disagreement drops below \varepsilon = 0.20:

clone pi(.|s=9): [0.061 0.818 0.061 0.061]
clone pi(.|s=10): [0.25 0.25 0.25 0.25]
  • Demonstrated vs. undemonstrated rows: Fourteen Adam steps push every demonstrated cell (such as s = 9) to \pi_{\textrm{bc}}(a^* \mid s) = 0.818 (\varepsilon = 0.182), while undemonstrated cell s = 10 receives zero gradient and stays uniform (0.250, disagreeing with \pi^* 3/4 of the time).

Exact State-Visitation Propagation

Evaluating Policies Without Sampling Noise

d_{t+1}^\pi(s') = \sum_{s \in \mathcal{S}} d_t^\pi(s)\,P_\pi(s' \mid s) = \big(d_t^\pi P_\pi\big)(s')

  • Exact 100-step success probability: Making terminal holes and the goal absorbing in P_\pi ensures that d_{100}^\pi(\textrm{goal}) equals the exact 100-step success rate.

Greedy vs. Sampling Deployment of the Clone

Measuring Deployment Success

Deploying the fitted clone either greedily (\mathrm{argmax}_a \pi_{\textrm{bc}}(a \mid s)) or by sampling (a_t \sim \pi_{\textrm{bc}}(\cdot \mid s), as language models sample tokens) reveals a 34-percentage-point drop:

        expert: reaches the goal 1.000, falls into a hole 0.000
  greedy clone: reaches the goal 1.000, falls into a hole 0.000
sampling clone: reaches the goal 0.660, falls into a hole 0.340
sampling clone, 1000 episodes of bc.act: reaches the goal 0.656
  • Why greedy deployment succeeds 100\%: On every cell of the 6-move path, the expert action has the highest probability (0.818 > 0.061), so argmax stays on the tube forever.
  • Why sampling deployment drops to 66.0\%: With \varepsilon = 0.182 per step, the chance of 6 error-free moves in a row is only 0.818^6 \approx 0.300, and off-path cells have uniform 1/4 policies.

Diagnosing Policy-Induced Distribution Shift

Why More Expert Data Cannot Help

Comparing the clone’s disagreement rate 1 - \pi_{\textrm{bc}}(\pi^*(s) \mid s) across three state distributions proves that the failure is distribution shift, not overfitting:

disagreement with the expert
  on the training pairs:        0.182
  on 100 fresh expert episodes: 0.182
  on the clone's own states:    0.216
clone of   1 expert episodes: reaches the goal 0.660
clone of  10 expert episodes: reaches the goal 0.660
clone of 100 expert episodes: reaches the goal 0.660
  • Zero generalization gap on d^{\pi^*}: The clone errs 18.2\% on its 18 training pairs and 18.2\% on 100 fresh expert episodes, so cloning 1, 10, or 100 expert episodes produces the exact same 66.0\% table.
  • Higher error on d^{\pi_{\textrm{bc}}}: Weighted by its own state occupancy, the clone’s error jumps to 21.6\% because its own mistakes carry it into unvisited cells where its error rate is 75\%.

Distribution Shift vs. Missing Expert Coverage

Two Distinct Data Deficiencies

On slippery ice, the expert itself slips into different cells across episodes, allowing us to contrast finite-sample missing coverage against distribution shift:

share of 200 datasets whose greedy clone is below half the expert (0.730):
  expert episodes per dataset  1: 32.0%
  expert episodes per dataset  3: 1.5%
  expert episodes per dataset 10: 0.0%
  • Missing coverage vanishes with n: On slippery ice, 1 expert episode misses critical cells 32.0\% of the time, 3 episodes fail 1.5\% of the time, and 10 episodes cover the expert’s reachable states completely (0.0\% failures).
  • Distribution shift persists for all n: Even with infinite expert data (n \to \infty), states outside the expert’s support (d^{\pi^*}(s) = 0) never receive labels.

The Compounding Error Theorem

Quadratic vs. Linear Horizon Scaling

J(\pi^*) - J(\hat{\pi}) \leq \begin{cases} \varepsilon\,T(T + 1)/2 & \text{error } \varepsilon \text{ on } d_t^{\pi^*} \\ u\,\varepsilon\,T & \text{error } \varepsilon \text{ on } d_t^{\hat{\pi}} \end{cases}

  • O(\varepsilon T^2) under behavior cloning: The first mistake at step t forfeits up to all T - t + 1 remaining steps.
  • O(u\varepsilon T) via hybrid telescoping: Consecutive hybrids \pi_{k-1}, \pi_k differ only at step k on d_k^{\hat{\pi}}, losing at most u\varepsilon per step.

Quadratic vs. Linear Error Growth on a 64-Step Chain

Visualizing the Horizon Penalty

On a T-step chain (expert earns 1 per step, imitators err with \varepsilon = 0.01), cloning diverges from recovery (u = 1):

  • Cloned imitator: Earns step-t reward with probability (1-\varepsilon)^t, losing 17.03 rewards at T = 64 (tracking \varepsilon T(T+1)/2 = 20.80).
  • Recovering imitator: Returns to the path after a 1-step penalty (u = 1), losing exactly \varepsilon T = \mathbf{0.64} rewards—a 27\times reduction.

lost return at T=64: cloned 17.03 (eps T(T+1)/2 = 20.80), recovering 0.64 (eps T = 0.64)

Where the Clone Strays on Calm FrozenLake

State Visitation Map

Tracing the deployed clone’s state visitation probabilities across the 16 cells shows exactly where it exits the expert’s 6-move tube:

  • Three off-path exits (dashed arrows): The clone leaves the blue expert path in 17.2\% of episodes—stepping right from cell 0 into cell 1, or up/right from cells 9 and 14 into cell 10.
  • Unlabeled drift: Once in cell 1 or 10, the clone acts uniformly at random (1/4 per direction), often wandering into holes 5, 7, and 11.

Decomposing the Clone’s 34-Point Performance Drop

On-Path Fit Error vs. Off-Path Distribution Shift

Making the off-path cells absorbing partitions the clone’s 34.0-point loss (1.000 \to 0.660) into on-path errors vs. off-path distribution shift:

the clone leaves the expert path in 0.172 of its episodes, entering cells [ 1 10]
it reaches the goal in 0.715 of the episodes that stay on the path, 0.394 of those that leave it
a learner with the same error at every cell reaches the goal 0.735
  • On-path hole falls (23.6 points): In the 82.8\% of episodes that never leave the path, the clone reaches the goal 71.5\% of the time (0.828 \times 0.285 = 0.236 lost to adjacent holes 5 and 12).
  • Off-path failures (10.4 points): In the 17.2\% of episodes that exit the path, only 39.4\% recover (0.172 \times 0.606 = 0.104 lost); labeling all off-path cells with the same 18.2\% error lifts total success from 0.660 to 0.735.

DAgger: Dataset Aggregation

Collecting States from the Learner, Labels from the Expert

  • Interactive relabeling (Ross et al., 2011): Roll out the current learner \hat{\pi}_k and query the expert \pi^* on the states the learner actually visits.
  • Aggregating all rounds: Append relabeled pairs to \mathcal{D}_k = \mathcal{D}_{k-1} \cup \mathcal{D}_{\textrm{new}} and refit \hat{\pi}_{k+1} so earlier states are never forgotten.
def relabel(env, expert, learner, num_episodes, rng):
    """Roll the learner, sampling its actions; label its states with the
    expert's actions."""
    visited = []
    for _ in range(num_episodes):
        s, done = env.reset()[0], False
        while not done:
            visited.append(s)
            s, _, terminated, truncated, _ = env.step(learner.act(s, rng))
            done = terminated or truncated
    visited = np.array(visited)
    return visited, expert[visited]

Four DAgger Rounds Recover the Off-Path Loss

Empirical Convergence to the Full-Coverage Ceiling

Running 4 rounds of DAgger (10 learner episodes per round across 10 seeds) closes the distribution-shift gap from 0.660 to the 0.735 full-coverage ceiling:

round 0:  18 labels at  6 states, success 0.660 (seeds: 0.660 to 0.660; medians over 10 seeds)
round 1:  84 labels at  8 states, success 0.710 (seeds: 0.649 to 0.735; medians over 10 seeds)
round 2: 152 labels at  9 states, success 0.717 (seeds: 0.652 to 0.735; medians over 10 seeds)
round 3: 218 labels at 11 states, success 0.735 (seeds: 0.710 to 0.735; medians over 10 seeds)
round 4: 283 labels at 11 states, success 0.735 (seeds: 0.717 to 0.735; medians over 10 seeds)
  • Why DAgger reaches 0.735 and stops there: Once the learner visits and receives expert labels at cells 1, 2, 6, and 10, every reachable state has \varepsilon = 0.182; the remaining gap (0.735 vs. 1.000) is the classifier’s per-step error \varepsilon.

Supervised Fine-Tuning and On-Policy Distillation

Imitation Learning in Large Language Models

In the token-level MDP of §14.1, standard post-training stages of large language models map directly onto behavior cloning and DAgger:

Imitation Learning Concept Language Model Post-Training Counterpart
State s_t and action a_t Prompt plus generated prefix (x, y_{<t}) and next token y_t
Behavior cloning on \mathcal{D}^* Supervised Fine-Tuning (SFT): cross-entropy on curated expert responses
Deployment distribution shift Autoregressive exposure bias as the model conditions on its own sampled tokens
Recovery cost u vs. horizon T u is small for a stylistic synonym, but u \approx T - t for an early arithmetic sign error
DAgger with an interactive expert On-policy distillation: student rolls out prefixes y_{<t} \sim \pi_\theta, teacher labels \pi^*(\cdot \mid x, y_{<t})

Concept Check: Imitation Learning and DAgger

Check Your Understanding

Test your understanding of distribution shift, compounding error, and DAgger:

  1. Data scaling: On calm FrozenLake, why does increasing the behavior-cloning dataset from 3 expert episodes to 1{,}000 expert episodes leave the sampling clone’s success rate completely unchanged at 0.660?
  2. Quadratic vs. linear bound: Under what task condition does part (ii) of the compounding error proposition (u\,\varepsilon\,T) collapse back to the quadratic O(\varepsilon\,T^2) rate even when \varepsilon is small on d_t^{\hat{\pi}}?
  3. Closing the remaining gap: After 4 rounds of DAgger on calm FrozenLake, the learner’s success rate saturates at 0.735. What must change to push its success rate from 0.735 toward 1.000?

Answers:

  1. On deterministic calm ice, the expert follows the exact same 6-cell path in every episode; adding 1{,}000 episodes just repeats those 6 pairs without ever labeling off-path cells 1, 2, 3, 6, 10.
  2. When a single mistake is fatal or unrecoverable (such as falling into a hole), the one-step recovery cost u equals the remaining horizon \approx T - t, making u\,\varepsilon\,T = \Theta(\varepsilon\,T^2).
  3. We must reduce the classifier’s per-step fit error \varepsilon below 0.182 (e.g., training for more steps or deploying greedily); DAgger only removes distribution shift, not the base classification error \varepsilon.

Summary: Imitation Learning Methods

Key Takeaways

Method / Regime Training Distribution Expected Return Shortfall & Key Properties
Behavior Cloning (BC) Expert states s \sim d_t^{\pi^*} \leq \varepsilon T(T+1)/2 = O(\varepsilon T^2); no environment interaction or reward needed
Greedy BC Deployment Expert states s \sim d_t^{\pi^*} Succeeds on deterministic tasks if \mathrm{argmax}_a \hat{\pi}(a \mid s) = \pi^*(s) on path
DAgger Aggregated learner states s \sim d_t^{\hat{\pi}_k} \leq u\,\varepsilon\,T = O(u\varepsilon T) for recoverable tasks; requires interactive expert on call
Language Model SFT Curated human/teacher prefixes Suffers exposure bias over long reasoning chains as errors shift context
On-Policy Distillation Student prefixes relabeled by teacher Implements DAgger for LLMs using teacher logits \pi^*(\cdot \mid x, y_{<t})

Up next (§14.6 Optimal Control & §14.7 Policy Gradient): When no expert is available to imitate, we either differentiate directly through known continuous physics \mathbf{x}_{t+1} = f(\mathbf{x}_t, \mathbf{u}_t) via LQR, iLQR, and MPC (§14.6), or optimize a parameterized policy \pi_\theta(a \mid s) from sampled scalar rewards via the score-function policy gradient (§14.7).