Imitation and Inverse Reinforcement Learning
A self-driving car must learn to merge onto a highway. But no engineer can write down a reward function that captures "merge smoothly, like a competent human driver would." Hand-crafted rewards for such tasks are brittle. Reward a car for staying in its lane and it may learn to sit motionless at the lane's center. Reward it for progress and it may learn to tailgate. Yet we often have something much easier to obtain than a reward function — recordings of an expert doing the task well. Imitation learning (IL) and inverse reinforcement learning (IRL) are the two families of methods that turn such demonstrations into competent policies. They do this either by copying the expert's behavior directly or by first recovering the reward function that explains it. This problem matters because reward design is the hidden bottleneck of applied reinforcement learning. In robotics, autonomous driving, dialogue systems, and game AI, specifying a good reward is hard. It must induce exactly the desired behavior, without unintended shortcuts. This is often harder than solving the control problem itself. Demonstrations sidestep this: a human teleoperating a robot arm, or a logged trajectory of a skilled trader, encodes the desired behavior implicitly. The question this article answers is how to turn that behavioral signal into a policy. That policy must generalize beyond the exact states seen in the demonstrations. The big picture divides into two philosophies. Behavioral cloning treats the problem as supervised learning. It fits a policy to (state, action) pairs from the expert via maximum likelihood, and hopes it generalizes. This is simple but fragile, because small prediction errors compound over a trajectory. This phenomenon is called covariate shift or compounding error. Inverse reinforcement learning instead asks why the expert acted that way. It infers a reward function under which the expert's behavior is (near-)optimal. It then solves the resulting RL problem to get a policy. That policy is robust to the very distribution shift that dooms naive cloning. Adversarial imitation methods, most notably GAIL, blend the two approaches. They use a discriminator to define an implicit reward. They train a policy against it with Deep Policy Gradient Methods, without ever explicitly recovering a reward function. This article builds the full picture. It explains why behavioral cloning fails asymptotically. It shows how DAgger patches it with interactive data collection. It shows how the maximum-entropy IRL framework makes reward inference well-posed. It shows how adversarial imitation learning turns IRL into a scalable, GAN-like training procedure. We connect these ideas to Offline Reinforcement Learning, since demonstrations are a form of offline data. We also foreshadow how these same ideas underlie reward modeling in RLHF.
- Behavioral cloning (BC) fits expert (state, action) pairs via supervised learning; it is simple but suffers compounding errors that grow quadratically in trajectory length.
- DAgger fixes covariate shift by iteratively querying the expert on states visited by the learned policy, achieving linear (not quadratic) error growth.
- Inverse reinforcement learning (IRL) recovers a reward function under which expert behavior is optimal, addressing the ill-posedness of "any policy can be optimal for some reward" via maximum-entropy regularization.
- Maximum Entropy IRL formulates reward inference as matching feature expectations while maximizing entropy over trajectories, yielding a convex, well-posed optimization.
- Generative Adversarial Imitation Learning (GAIL) replaces explicit reward recovery with a discriminator that distinguishes expert from policy trajectories, and trains the policy to fool it — recovering expert-level behavior without ever solving an inner RL loop to convergence for each reward guess.
- These techniques are foundational to robotics, autonomous driving, and reward modeling pipelines that underlie RLHF Connections and connect naturally to Hierarchical Reinforcement Learning when demonstrations decompose into sub-skills.
Imitation learning copies expert behavior; inverse reinforcement learning infers the expert's intent, and both exist because compounding prediction errors make naive supervised cloning fail at long-horizon control.
The idea
Imitation learning is the problem of learning a policy from a dataset of expert demonstrations , where each trajectory was generated by an expert policy , typically without access to a reward signal or even to the environment's transition dynamics during training. The simplest instantiation, behavioral cloning (BC), discards the sequential structure of the problem entirely and treats as an i.i.d. supervised dataset of pairs, minimizing
This is easy to optimize but ignores that the test-time state distribution is generated by rolling out itself, not by — a mismatch that is the central technical obstacle in this entire chapter.
Inverse reinforcement learning (IRL) takes a different stance: instead of directly mimicking actions, it posits that the expert is (approximately) optimal under some unknown reward function , and tries to recover from the demonstrations. Once a plausible is found, an ordinary RL algorithm is run against it to produce a policy. The appeal is generalization: a reward function is a more compact, more transferable description of what the expert is trying to achieve than a giant lookup table of state-action pairs, and a policy trained to optimize that reward is robust to distribution shift by construction — if it drifts into an unfamiliar state, it can still evaluate what action locally increases reward, whereas a cloned policy has no such fallback. IRL is fundamentally ill-posed: infinitely many reward functions (including the trivial ) make any fixed policy optimal. Resolving this ambiguity is the technical heart of the field, addressed principally through the maximum entropy principle, which selects, among all rewards consistent with the observed behavior, the one whose induced trajectory distribution has maximum entropy subject to matching the expert's feature statistics — a well-justified choice because it makes no assumptions beyond what the data supports (any more "peaked" distribution would encode extra, unsupported preferences). Adversarial imitation learning (notably GAIL) reframes the entire IRL-then-RL pipeline as a two-player game between a policy (generator) and a discriminator, sidestepping the need to ever explicitly represent or interpret , much as Deep Policy Gradient Methods use a value or advantage estimate without needing a closed-form value function.
How it works
1. Behavioral cloning and why it fails
BC minimizes negative log-likelihood over the expert dataset with ordinary supervised learning machinery (cross-entropy for discrete actions, Gaussian NLL for continuous control). The failure mode is compounding error: suppose the learned policy makes a state-prediction-conditional mistake with probability at each of timesteps. Once it makes a mistake, it enters a state slightly outside the expert's data distribution, where its error probability is not bounded by the same (no training signal there), so errors compound. This yields expected total cost that scales as in the worst case, versus the one would hope for. This quadratic blowup is the reason self-driving prototypes trained by pure BC tend to drift off-road: a tiny steering error puts the car in a state (partially off-lane) never seen in expert data, where the policy's behavior is essentially undefined and the error compounds.
2. DAgger: closing the distribution-shift gap
Dataset Aggregation (DAgger) fixes this by iteratively collecting states from the current policy's own rollouts, querying the expert for the correct action at those states, and retraining — so the training distribution converges to the policy's own state distribution rather than staying frozen at the expert's. ``` Algorithm: DAgger (Dataset Aggregation) Input: expert policy π_E (queryable), environment, number of iterations N Initialize dataset D ← ∅ Initialize policy π_1 arbitrarily (e.g., random or BC-pretrained) for i = 1 to N:
# Roll out the CURRENT learned policy (not the expert) to collect states Sample T-step trajectories using policy π_i (possibly mixed with π_E early on) for each visited state s in these trajectories: query expert action a = π_E(s) D ← D ∪ {(s, a)}
# Retrain policy by supervised learning on ALL data seen so far π_{i+1} ← argmin_θ (1/|D|) Σ_{(s,a) ∈ D} -log π_θ(a | s) return best π_i on held-out validation rollouts ``` Note the key structural difference from BC: the states in are drawn from mixtures of the learner's own induced state distribution across iterations, not solely from 's distribution. This requires an interactive expert (a human in the loop, or a scripted oracle, or a privileged-information controller) — a real cost that pure offline BC does not incur, connecting this tradeoff directly to when Offline Reinforcement Learning must be used instead (no further environment or expert interaction is possible).
3. Maximum Entropy Inverse Reinforcement Learning
MaxEnt IRL assumes the expert's trajectory distribution follows a Boltzmann form over cumulative reward:
where is typically linear in features, (or a neural network in deep variants). Learning maximizes the log-likelihood of the observed expert trajectories under this model:
The gradient of this objective has a clean and interpretable form:
i.e., the difference between the expert's feature expectations and the feature expectations under the current reward's induced (soft-optimal) policy. At the optimum this difference is zero — the learned reward makes the model's expected feature counts match the expert's exactly, which is precisely the maximum-entropy solution consistent with the observed statistics (by a Lagrangian/duality argument: matching feature expectations under a maximum-entropy trajectory distribution is the dual of maximizing the exponential-family log-likelihood above). ``` Algorithm: MaxEnt IRL (tabular / feature-linear version) Input: expert trajectories D, feature map φ(s,a), MDP transition dynamics Initialize θ arbitrarily repeat until convergence:
# 1. Solve for the soft-optimal policy under current reward r_θ = θᵀφ Compute soft value function via soft Bellman backup: Q_soft(s,a) = r_θ(s,a) + γ E_{s'}[ V_soft(s') ] V_soft(s) = log Σ_a exp(Q_soft(s,a)) # softmax, not max Derive soft policy: π_θ(a|s) = exp(Q_soft(s,a) - V_soft(s))
# 2. Compute expected state-visitation frequencies under π_θ
# (forward pass through the MDP, propagating visitation probabilities) μ_θ(s,a) ← state-action visitation frequencies induced by π_θ
# 3. Gradient step: match feature expectations grad ← (1/|D|) Σ_{τ∈D} Σ_t φ(s_t,a_t) - Σ_{s,a} μ_θ(s,a) φ(s,a) θ ← θ + α · grad return θ, π_θ ``` This tabular version requires solving a full soft-value-iteration inside every gradient step — expensive, and infeasible in continuous or high-dimensional state spaces (the inner loop is itself a planning problem). This computational bottleneck is exactly what motivates adversarial imitation learning.
4. Generative Adversarial Imitation Learning (GAIL)
GAIL reframes IRL as: find a policy whose state-action occupancy measure matches the expert's occupancy measure , measured via Jensen–Shannon divergence, mirroring exactly the generator/discriminator structure of a GAN. A discriminator is trained to distinguish expert transitions from policy-generated ones; the policy is trained, via any policy-gradient method, to maximize a reward signal derived from fooling the discriminator. ``` Algorithm: GAIL Input: expert trajectories D_E, environment, policy π_θ, discriminator D_φ Initialize θ, φ randomly for iteration = 1, 2, ...:
# 1. Roll out current policy to collect trajectories Sample trajectories τ_π using π_θ → dataset D_π of (s,a) pairs
# 2. Update discriminator to separate expert from policy data
# D_φ(s,a) → 1 means "looks like expert", → 0 means "looks like policy" φ ← φ + α_D · ∇_φ [ E_{(s,a)~D_E}[ log D_φ(s,a) ] + E_{(s,a)~D_π}[ log(1 - D_φ(s,a)) ] ]
# 3. Define an imitation reward from the discriminator, e.g.
# r(s,a) = -log(1 - D_φ(s,a)) (or log D_φ(s,a) )
# then update the policy with any policy-gradient method (e.g. TRPO/PPO)
# to maximize E[ Σ_t γ^t r(s_t,a_t) ] (plus optional causal-entropy bonus) θ ← θ + α_π · PolicyGradientUpdate(π_θ, r, D_π) return π_θ ``` The discriminator implicitly defines a reward: as becomes indistinguishable from , everywhere, and the imitation reward saturates — a signal, analogous to GAN convergence, that occupancy measures have matched. Crucially, GAIL never explicitly represents as an interpretable object; the discriminator is a reward classifier, not a portable reward function, which is a genuine limitation relative to explicit IRL when transfer to a new environment or task is the goal.
Complexity & correctness
Behavioral cloning. Time complexity per training step is that of ordinary supervised learning: per epoch, where is the cost of a forward/backward pass. This is cheap and requires no environment interaction. The correctness caveat is the crucial one: even if the per-step action-prediction error is bounded by everywhere the expert data covers, the expected total cost incurred by rolling the learned policy out for steps is in the worst case (Ross & Bagnell's analysis). Sketch: at each timestep there is probability roughly of a mistake; once a mistake occurs, the agent may enter a state distribution never seen at training time, after which errors are essentially unconstrained (worst-case cost per remaining step), and a mistake at time can cost up to additional steps of accumulated regret — summing over gives .
DAgger. Each iteration costs one policy rollout of length plus one expert query per visited state plus a retraining pass, so total cost after iterations is , dominated in practice by the number of expert queries, which is the scarce resource (a human demonstrator, or an expensive privileged oracle). The correctness guarantee is the point of the algorithm: because training data accumulates from the learner's own induced state distribution across iterations (an online-learning / no-regret argument over the sequence of retrained policies), DAgger achieves expected total cost — linear, not quadratic, in horizon — assuming the underlying no-regret online learner converges (this follows from a reduction of imitation learning to no-regret online classification, where the sequence of policies constitutes an online learning process over changing state distributions).
MaxEnt IRL (tabular). Each gradient step requires solving soft value iteration to convergence, costing per Bellman backup (or for sparse transitions) times the number of backups to converge, repeated over gradient steps — so total cost is roughly for backups per inner solve. This is why tabular MaxEnt IRL is restricted to small, enumerable state spaces; scaling to continuous or high-dimensional states requires either sampling-based approximations (Guided Cost Learning) or abandoning explicit reward recovery altogether (GAIL). Correctness: the MaxEnt formulation is a strictly concave maximum-likelihood problem in when the reward is linear in features and the induced trajectory distribution is in the exponential family, so gradient ascent converges to the unique global optimum where model feature expectations equal empirical feature expectations — this is exactly the maximum-entropy distribution consistent with the observed statistics, by the standard duality between maximum entropy under moment constraints and maximum likelihood in an exponential family.
GAIL. Each iteration costs one policy rollout ( environment steps), one discriminator gradient step ( per minibatch), and one policy-gradient update using an algorithm like TRPO or PPO (inheriting whatever per-step complexity that method has — typically for computing gradients plus the cost of a trust-region or clipped-surrogate optimization). The correctness argument mirrors GAN theory: at the Nash equilibrium of the min-max game, , i.e., the policy's state-action occupancy exactly matches the expert's, provided the discriminator and policy classes are expressive enough and the alternating optimization converges (a caveat as real as it is for GANs — in practice GAIL training can oscillate or mode-collapse, and convergence guarantees are local, not global, once neural function approximation replaces the tabular/linear setting).
Honest tradeoffs. BC is cheapest but least robust; DAgger is more robust but requires an interactive, queryable expert, which is often unavailable (offline logs cannot be re-queried, directly motivating Offline Reinforcement Learning approaches when only static datasets exist); IRL recovers an interpretable, transferable reward but is computationally heavy and only well-posed under strong regularization assumptions; GAIL is sample-efficient in expert demonstrations but sample-inefficient in environment interactions (it needs many on-policy rollouts, exactly as Deep Policy Gradient Methods do), and it sacrifices reward interpretability and transfer.
Worked example
Consider a 5-state deterministic gridworld corridor, states (goal), where the expert always moves right (). We trace how each method handles a single injected error.
Setup. Feature map one-hot encoding of position. The expert trajectory is , all actions "".
BC trace. Suppose the cloned policy has learned , — a small 10% error at , purely because was underrepresented in training data relative to . On a rollout, with probability 0.1 the agent steps back to . But the training data at was collected from expert trajectories that only ever visited moving forward from — the policy has no signal on "what to do at having just failed a step at ," so let's say its behavior there degrades further, e.g., now (never trained on this branch). The point is quantitative: the error at creates a novel state-distribution problem at that compounds, exactly the mechanism, not merely a one-off 10% chance of one wasted step.
| Iteration | Policy behavior at | Resulting state after mistake | Policy behavior there (untrained region) |
|---|---|---|---|
| BC, no correction | 10% chance of "" | (rarely visited in training as a post-mistake state) | further drift (30% wrong action) |
DAgger trace. After BC pretraining, we roll out and it makes exactly this mistake, visiting via the erroneous backward step. DAgger queries the expert at this specific, off-expert-distribution state: . This pair — critically, reached via the policy's own error, not the expert's nominal path — is added to . After retraining, is now correctly reinforced even in this "recovery" context, so a future mistake at no longer compounds: the agent self-corrects at and proceeds to the goal. This is the mechanism, concretely, by which DAgger converts into : every mistake teaches the policy how to recover from that exact mistake.
MaxEnt IRL trace. Suppose instead we are given only the expert trajectory (no queryable expert) and must recover a reward. Empirical feature expectations from the demonstration: state (one step from goal) is visited once, as is every other state, giving uniform empirical counts along the corridor. We initialize (reward zero everywhere), compute the soft-optimal policy (uniform random, since all -values are equal), and get feature expectations that overweight early states (a random walker lingers near the start and rarely reaches ). The gradient is strongly positive at and negative at , so increases reward near the goal. Iterating this, converges to a monotonically increasing reward along the corridor — precisely what makes "always move right" the optimal policy without ever having been told "reach " as an explicit goal predicate. This reward, unlike a cloned policy, would also correctly guide behavior if the corridor were extended to at test time, because it encodes directional progress, not memorized states — the central generalization advantage IRL buys over BC.
Common pitfalls & traps
| Pitfall | Why it happens | Consequence | Fix |
|---|---|---|---|
| Treating BC as if i.i.d. supervised learning guarantees hold at deployment | Ignoring that test-time states are self-generated, not sampled from | Compounding drift, catastrophic failure on long horizons | Use DAgger, add noise-injection/dropout during data collection, or use offline RL regularizers |
| Reward ambiguity in naive IRL ("any policy is optimal for reward ") | IRL is underdetermined without a selection principle | Degenerate or trivial recovered rewards | Use maximum-entropy (or other) regularization to pick a unique, well-justified solution |
| Confusing GAIL's discriminator output with a portable reward function | The discriminator is trained jointly with a specific policy and saturates near at convergence | Reward is not meaningful outside the training distribution/environment; cannot transfer to a new task | If transfer is the goal, use explicit IRL (e.g., AIRL) designed to disentangle reward from dynamics |
| Overfitting BC to a small demonstration set | Expert data is expensive, often only tens–hundreds of trajectories | Policy memorizes near-exact states, fails to generalize to nearby states | Data augmentation, regularization, or DAgger-style online correction |
| Ignoring that DAgger requires a queryable expert at arbitrary states | Assuming the same static log used for BC suffices | Cannot label the off-distribution states the learner visits; algorithm silently degrades to BC | Ensure an interactive expert (human, simulator oracle) is genuinely available before choosing DAgger |
| Non-stationary discriminator causing GAIL training instability | Alternating min-max optimization, similar to GAN training pathologies | Oscillating policy quality, mode collapse onto a narrow behavior subset | Trust-region policy updates (TRPO/PPO), gradient penalties on the discriminator, reward shaping via entropy bonuses |
Pioneers & history
Imitation learning traces back to control-theoretic ideas of learning from demonstration in robotics, but its modern theoretical foundation and its connection to inverse optimal control were shaped by a lineage of researchers bridging control theory, statistical learning theory, and deep RL.
Origins · 1 minAndrew Y. Ng and how this was discovered
Andrew Ng, working with Stuart Russell, posed the inverse reinforcement learning problem in a precise algorithmic form in 2000, framing it as a linear-programming feasibility problem over reward functions consistent with observed optimal behavior, and later contributed apprenticeship-learning algorithms that matched feature expectations between expert and learned policies — a direct conceptual ancestor of MaxEnt IRL.
Russell's 1998 formulation asked how an agent should infer a reward function purely from observed behavior, motivated partly by cognitive-science questions about how humans and animals learn objectives by watching others, seeding what later became a central concern of value alignment and, downstream, reward modeling for language models.
Where this matters
Autonomous driving stacks use variants of imitation learning (often DAgger-like online correction and large-scale behavioral cloning from human driving logs) as a core component alongside planning and perception modules, precisely because reward-shaping "drive safely and comfortably" by hand is intractable. Robotic manipulation research relies heavily on learning-from-demonstration pipelines, teleoperating a robot arm and then using GAIL-style or BC-with-DAgger training to generalize beyond the exact teleoperated trajectories. Game-playing agents and NPC behavior modeling use imitation learning to bootstrap policies from human replays before fine-tuning with RL, since pure RL exploration from scratch in enormous action spaces (e.g., real-time strategy games) is prohibitively expensive without a good initialization. Most consequentially, the reward-modeling stage of RLHF pipelines used to align large language models is structurally an inverse-reinforcement-learning problem: human preference comparisons play the role of "expert demonstrations," a learned reward model plays the role of the recovered , and a policy-gradient method (often PPO) optimizes against that reward exactly as in the IRL-then-RL pipeline described here — a connection made explicit under RLHF Connections. When demonstrations naturally decompose into reusable sub-behaviors (e.g., "grasp," then "lift," then "place"), imitation and IRL methods interact closely with Hierarchical Reinforcement Learning, which structures policies around such recovered or cloned sub-skills.
Ask the tutor: How does Adversarial Inverse Reinforcement Learning (AIRL) modify GAIL's objective to recover a reward function that transfers across changes in environment dynamics?
Is imitation learning the same thing as supervised learning?
Not quite. Behavioral cloning reduces imitation learning to supervised learning by treating (state, action) pairs as i.i.d. training examples, but this reduction is imperfect because the deployment-time state distribution depends on the very policy being trained — a feedback loop absent from ordinary supervised learning. This is why methods like DAgger exist: they repair the reduction by making the training distribution track the policy's own induced distribution, effectively turning imitation learning into a sequence of supervised problems coupled through an online-learning argument, rather than a single static supervised fit.
Why is inverse reinforcement learning considered "ill-posed"?
Because many different reward functions can make the same expert trajectories look optimal — including the degenerate reward that is zero (or constant) everywhere, under which every policy is trivially optimal. Without additional structure, IRL as a bare feasibility problem has no unique solution, and naive formulations can output degenerate or uninformative rewards. Maximum-entropy IRL resolves this by adding a specific, principled tie-breaking rule: among all rewards consistent with the expert's observed feature statistics, prefer the one whose induced trajectory distribution has maximum entropy, avoiding unsupported extra assumptions about the expert's preferences.
Does GAIL recover the true reward function of the expert?
No, not directly, and this is one of its main limitations. GAIL's discriminator is trained jointly with a specific policy in a specific environment, and at convergence it saturates toward 1/2 everywhere rather than converging to a stable, interpretable reward. If you need a reward function that transfers to a different environment or dynamics (e.g., sim-to-real transfer), you typically need methods explicitly designed to disentangle reward from dynamics, such as Adversarial Inverse Reinforcement Learning (AIRL), rather than plain GAIL.
When should I prefer behavioral cloning over IRL or GAIL?
Prefer BC when you have abundant, high-coverage expert demonstrations, a short effective horizon (so compounding error has little room to accumulate), and no ability to interact further with an expert or environment during training — conditions that closely resemble those handled by Offline Reinforcement Learning. IRL and GAIL are preferable when demonstrations are scarce relative to the complexity of the task, when the task horizon is long enough that compounding error would be severe, or when you expect deployment conditions to differ somewhat from the exact demonstrated states, since reward-driven policies generalize via the recovered objective rather than via memorized state-action mappings.
How expensive is running GAIL compared to behavioral cloning in practice?
Substantially more expensive in terms of environment interaction. Behavioral cloning needs zero environment interactions beyond the fixed demonstration dataset, whereas GAIL requires repeated on-policy rollouts to train both the discriminator and the policy, inheriting the sample complexity characteristics of whatever policy-gradient method it uses internally (commonly TRPO or PPO). In exchange, GAIL typically needs far fewer expert demonstrations than BC to reach comparable asymptotic performance, since it is matching distributional statistics rather than fitting a direct action-prediction function, so the tradeoff is expert-data efficiency versus environment-interaction efficiency.
Can imitation learning be combined with reinforcement learning rather than treated as an alternative?
Yes, and this is common in practice. A frequent pipeline pretrains a policy with behavioral cloning to get a reasonable initialization, then fine-tunes it with an RL algorithm (using either the environment's true reward if available, or a learned/recovered reward from IRL) to correct the compounding-error weaknesses of pure cloning. This hybrid approach is closely related to how Deep Policy Gradient Methods are often warm-started, and it foreshadows RLHF pipelines, which combine a supervised fine-tuning stage (essentially BC on human-written responses) with a subsequent reward-model-driven RL stage.
What role does the discount factor or horizon play in choosing between these methods?
Longer horizons make behavioral cloning's compounding-error problem more severe, since the bound grows quadratically with horizon length , making DAgger, IRL, or GAIL comparatively more attractive as tasks get longer. Conversely, for short-horizon or single-step decision tasks (e.g., one-shot classification-like control decisions), the distribution-shift problem is negligible, and plain behavioral cloning is often the simplest, cheapest, and perfectly adequate choice, with no need for the added machinery of interactive querying or adversarial training.