Imitation Learning
Vision-Language-Action robot models from groups like Physical Intelligence and Google DeepMind are mostly trained by imitation, not by reward, and driving research leans on imitation too. When exploration is dangerous (driving), expensive (surgery), or slow (real robots), cloning the experts gets you surprisingly far. The hard part isn't the algorithm; it's the covariate shift trap, which is why DAgger and GAIL were invented.
After this lesson, you will be able to:
- Train a policy from expert demonstrations using Behavioral Cloning, supervised learning on (state, action) pairs, and recognize the covariate-shift trap
- Apply DAgger to fix BC's compounding errors by aggregating expert corrections during agent rollouts, and explain why one extra training round per iteration restores performance
- Recover a reward function from expert behavior with Inverse RL (Maximum Entropy IRL, GAIL, AIRL), and decide when reward inference beats reward design
- Pick imitation vs RL based on whether you have abundant expert data, dangerous exploration, or the goal of exceeding the expert
Before you start
Don't worry if "imitation learning" sounds like cheating after the elegance of policy gradients, it is a very common first step in practice, and the math is much friendlier than computing advantage estimates.
#When Reward Design Is the Hard Part
Two big families of imitation learning sit on either side of a fork:
- Behavioral Cloning + DAgger: directly mimic the expert's actions. Supervised learning on trajectories.
- Inverse RL (IRL). Infer the expert's reward function, then run RL on it. More principled, harder to train.
#Behavioral Cloning: Supervised Learning on Trajectories
The simplest possible imitation learner. Given expert dataset D = , train a policy π_θ to predict a from s with cross-entropy or MSE loss:
Behavioural cloning is not just any supervised fit: with the usual log loss it has an exact reading as matching the expert's action distribution, and with a squared error it is maximum likelihood for a Gaussian policy. The derivation below shows this, and it also shows why BC only constrains the policy on states the expert visited. It is optional reading.
#The Covariate-Shift Trap
The quadratic growth can be derived with a short union-bound argument. It is optional reading.
#DAgger: Bring the Expert Back
DAgger's drawback is the obvious one: you need an interactive expert during training. For a human teleoperator, this is expensive, every iteration requires hours of new annotations. For a scripted/MPC expert, it's free; for a foundation-model-as-expert (e.g., asking GPT-4 what to do), it's cheap.
DAgger removes the quadratic term by training on the states the learner itself visits. The derivation has two parts: the first shows how a loss measured on the learner's own states controls the extra cost, and the last step says why the aggregated dataset lets DAgger make that loss small. It is optional reading.
Move the mistake chance eps and the horizon T, and watch behaviour cloning's cost climb far faster than DAgger's straight line as T grows, because one mistake puts the learner in states the expert never showed.
#Inverse RL: Recover the Reward Function
When the reward is linear in features, r_theta(s, a) = theta dot f(s, a), the gradient in the code comment below has a short derivation. Write f(tau) for the total features along trajectory tau. It assumes deterministic dynamics and a fixed set of candidate trajectories, as in Ziebart's original setting. It is optional reading.
#GAIL: Adversarial Imitation
The GAIL game has a clean meaning that the lesson states without proof: the discriminator's best response turns the objective into the Jensen-Shannon divergence between how often the learner and the expert visit each state-action pair. This is stated and proved in Ho and Ermon (2016). The GAN version of the argument is derived in Generative Models: GANs & VAEs, so the derivation below reuses it. It is optional reading.
You have 1,000 expert demonstration trajectories from a teleoperator. The teleoperator is no longer available. You want to train a robotic-manipulation policy. Which approach?
#Hands-On: BC on a Gym Environment
torch and gymnasium, which this page does not have, so it is read-only. Copy it to Google Colab to run it.# Copy to Colab: needs torch and gymnasium, so it cannot run on this page.
# Behavioral Cloning on CartPole using a tiny PyTorch MLP
import gymnasium as gym
import torch
import torch.nn as nn
import numpy as np
env = gym.make("CartPole-v1")
obs_dim = env.observation_space.shape[0]
act_dim = env.action_space.n # 2 discrete actions
# --- 1. Generate "expert" demonstrations using a known-good heuristic ---
def expert_action(s):
# Hand-crafted controller: balance based on pole angle + cart velocity
pole_angle = s[2]
cart_vel = s[1]
return 1 if pole_angle + 0.1 * cart_vel > 0 else 0
def collect_expert_episodes(n=100):
data = []
for _ in range(n):
s, _ = env.reset()
done = False
while not done:
a = expert_action(s)
data.append((s.copy(), a))
s, r, term, trunc, _ = env.step(a)
done = term or trunc
states = torch.tensor(np.array([d[0] for d in data]), dtype=torch.float32)
actions = torch.tensor([d[1] for d in data], dtype=torch.long)
return states, actions
# --- 2. Train BC policy ---
class BCPolicy(nn.Module):
def __init__(self):
super().__init__()
self.net = nn.Sequential(
nn.Linear(obs_dim, 64), nn.ReLU(),
nn.Linear(64, 64), nn.ReLU(),
nn.Linear(64, act_dim),
)
def forward(self, s): return self.net(s)
def act(self, s):
with torch.no_grad():
logits = self.net(torch.tensor(s, dtype=torch.float32))
return torch.argmax(logits).item()
states, actions = collect_expert_episodes(100)
print(f"Collected {len(states)} (state, action) pairs from 100 expert episodes")
bc = BCPolicy()
opt = torch.optim.Adam(bc.parameters(), lr=3e-4)
loss_fn = nn.CrossEntropyLoss()
for epoch in range(20):
idx = torch.randperm(len(states))
for i in range(0, len(states), 64):
batch = idx[i:i+64]
logits = bc(states[batch])
loss = loss_fn(logits, actions[batch])
opt.zero_grad(); loss.backward(); opt.step()
if epoch % 5 == 0:
print(f"epoch {epoch}: loss = {loss.item():.4f}")
# --- 3. Evaluate cloned policy ---
returns = []
for _ in range(20):
s, _ = env.reset()
total_r = 0; done = False
while not done:
a = bc.act(s)
s, r, term, trunc, _ = env.step(a)
total_r += r
done = term or trunc
returns.append(total_r)
print(f"\nBC policy mean return over 20 eps: {np.mean(returns):.1f} +/- {np.std(returns):.1f}")
print(f"Expert (heuristic) gets ~500 (max episode length).")
print()
print("CHALLENGE: Add a DAgger loop. After every 5 epochs, roll out the BC policy")
print("for 10 episodes, query expert_action() at each visited state, and add those")
print("(state, expert action) pairs to the dataset. Compare convergence vs pure BC.")The block that follows runs here, because it uses only the Python standard library. It clones an expert on a small slippery grid with a lookup table, so you can see the covariate-shift gap and the DAgger fix without installing anything.
Tests: Check that BC succeeds less often than the expert, and that after a few DAgger rounds the success rate moves back toward the expert's.
#When Imitation Wins, When RL Wins
| Setting | Use IL | Use RL |
|---|---|---|
| Reward hard to specify (driving, manipulation) | ✅ | ❌ |
| Exploration dangerous or expensive | ✅ | ❌ |
| Plentiful expert demos | ✅ | ❌ |
| Goal: match expert performance | ✅ | ⚠️ |
| Goal: exceed expert (AlphaGo Move 37) | ❌ | ✅ |
| Reward signal is cheap and clear (games, sims) | ❌ | ✅ |
| No expert exists | ❌ | ✅ |
| Long-horizon credit assignment matters | ⚠️ | ✅ |
#Key Takeaways
- Behavioral Cloning is supervised learning on (state, action) pairs. Cheap, simple, and works when the test distribution matches the expert's; fails predictably under covariate shift due to compounding errors O(T²ε)
- DAgger fixes BC's covariate shift by aggregating expert relabels of policy-visited states. Improves the error bound to O(Tε), but requires an interactive expert during training
- Inverse RL recovers the expert's reward function instead of mimicking actions. More interpretable and transferable than BC, but each iteration solves a forward-RL problem, making it expensive at scale
- GAIL trains an adversarial discriminator to distinguish expert vs agent visitations. The agent maximizes "fool the discriminator" as a reward; converges in distribution to the expert without explicit reward design
- Many robotics (RT-2, Pi-0) and LLM (SFT, then RLHF) pipelines bootstrap from demonstrations and add RL polish
#Quick Check
A pure Behavioral Cloning policy has perfect test accuracy on held-out expert data, yet crashes within 30 steps in the real environment. What is happening?