Module contents
Lesson 10 of 33Core 105 min

Inverse reinforcement learning and adversarial imitation: essentials

Infer rewards from expert behaviour, derive maximum-entropy IRL, and compare adversarial occupancy matching with behavior cloning.

After this lesson you can

  • Explain why IRL is ill-posed and how assumptions such as margins and maximum entropy resolve it.
  • Derive the maximum-entropy IRL gradient as a difference of feature expectations.
  • Implement maximum-entropy IRL in a gridworld using soft value iteration.
  • Explain GAIL as occupancy-measure matching with a discriminator and relate it to GANs.
  • Decide when IRL or GAIL is worthwhile compared with behavior cloning in robotics.

Before you start

What did the expert seek?

A robot goes around an obstacle. Copying its actions can work in the same scene but does not say what to do if the obstacle moves. If we infer a preference for reaching a goal and avoiding collisions, another policy can optimize it in the new scene. This promise requires knowing how the goal and obstacle are represented; trajectories alone do not reveal a unique intention.

InteractiveMany rewards, one behaviour

Reward by cell; optimal arrows

-0.1
1.0
Selected cell1, 1
Policy matchesYes
Paint rewards by cell and compare optimal policies before and after adding a potential. The potential acts on transitions, not as another cell reward.
InteractiveFit visitation frequencies
Learned reward
0.1
−0.1
−0.1
0.0
0.0
0.1
−0.1
−0.1
0.0
0.0
0.1
−0.1
−0.1
0.0
0.0
0.1
0.0
0.0
0.0
0.0
0.1
0.0
0.0
0.0
0.1
Expert visits
4.2
1.2
0.4
0.1
0.1
2.2
0.7
0.2
0.1
0.0
1.0
0.4
0.1
0.0
0.0
0.5
0.2
0.1
0.0
0.0
0.2
0.1
0.0
0.0
0.1
Model visits
4.2
1.2
0.4
0.1
0.1
2.2
0.8
0.2
0.1
0.0
1.0
0.4
0.1
0.1
0.0
0.4
0.2
0.1
0.0
0.0
0.2
0.1
0.0
0.0
0.0
Expert − model
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
−0.1
0.0
0.0
0.1
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.1
30
0.4
L1 distance between visits0.479
A soft policy and its occupancy are calculated exactly on a finite grid. Compare visits and learned reward; the gradient is normalized visit difference.
InteractiveOccupancies and discriminator
Empirical expert
0.00
0.08
0.00
0.04
0.00
0.16
0.16
0.04
0.04
0.00
0.08
0.00
0.00
0.04
0.00
0.00
0.08
0.00
0.00
0.00
0.00
0.08
0.08
0.08
0.04
Generator policy
0.00
0.08
0.00
0.04
0.00
0.16
0.16
0.04
0.04
0.00
0.08
0.00
0.00
0.04
0.00
0.00
0.08
0.00
0.00
0.00
0.00
0.08
0.08
0.08
0.04
Categorical BC
0.00
0.08
0.00
0.04
0.00
0.16
0.16
0.04
0.04
0.00
0.08
0.00
0.00
0.04
0.00
0.00
0.08
0.00
0.00
0.00
0.00
0.08
0.08
0.08
0.04
−log(1−D*)
0.00
0.71
0.00
0.74
0.00
0.70
0.70
0.74
0.74
0.00
0.71
0.00
0.00
0.74
0.00
0.00
0.71
0.00
0.00
0.00
0.00
0.71
0.71
0.71
0.74
25
150
Jensen-Shannon0.0112
One-step toy: BC estimates frequencies and a generator minimizes JS divergence with an optimal discriminator. It does not train PPO or represent a full robot task.

An ambiguous inversion

Inverse reinforcement learning (IRL) observes policy trajectories and seeks a reward explaining them as good decisions under known or estimated dynamics. An RL problem can then be solved with the recovered reward. The process nests one optimization inside another: fitting reward requires approximately calculating the policy it would produce; in robotics this can be much more expensive than fitting actions with behavior cloning (BC).

Reward ambiguity is fundamental. Zero reward makes all policies optimal, including the observed one. Multiplying a reward by a positive factor preserves return ordering, although it changes a model’s behaviour at fixed temperature. Nor do we know whether the expert chose a route for safety, comfort or an unobserved preference. Selecting a solution requires assumptions: a feature family, margins, regularization, temperature or extra information.

A subtler transformation adds F(s,a,s′)=γΦ(s′)−Φ(s)F(s,a,s')=\gamma\Phi(s')-\Phi(s), with 0≤γ<10\leq\gamma<1 and bounded potential. Its telescoping discounted sum is −Φ(s0)-\Phi(s_0): the final term vanishes. From a fixed initial state it changes all policy values equally, preserving optimal actions. At finite horizon there is a terminal term γTΦ(sT)\gamma^T\Phi(s_T); the conclusion holds only if that term is handled, for example by imposing zero terminal potential. The first figure uses an infinite discounted horizon and displays cell potential beside the policy, with ties identified numerically.

Feature expectation matching assumes rθ(s)=θ⊤ϕ(s)r_\theta(s)=\theta^\top\phi(s). For a policy, μ(π)=Eπ[∑tγtϕ(st)]\mu(\pi)=\mathbb E_\pi[\sum_t\gamma^t\phi(s_t)] summarizes visits. If θ\theta belongs to a bounded set and policy and expert expectations are close, their returns are close uniformly over that family. It does not follow that their actions, safety or true reward coincide. Abbeel and Ng formulate apprenticeship learning using these expectations.

For example, take two features: discounted steps near an obstacle and discounted proximity to the goal. Two trajectories can have the same sum of both even if one grazes the obstacle and the other maintains uniform distance. If the representation does not distinguish these situations, matching expectations does not certify absence of contact. A minimum-distance feature might help, but must be computable from states and remain meaningful when the scene changes.

A simple result clarifies the bound’s role. If ∥θ∥2≤B\|\theta\|_2\leq B, Cauchy-Schwarz bounds the absolute return difference by B∥μ(πE)−μ(π)∥2B\|\mu(\pi_E)-\mu(\pi)\|_2. Scale BB matters: without limiting weights, a small distance gives no uniform guarantee. Expectations also need sufficient data; matching frequencies from a handful of demonstrations can fit sampling errors.

Maximum entropy and expected visits

Maximum-entropy IRL chooses a trajectory distribution satisfying feature constraints without introducing extra preferences. In a finite deterministic case with fixed horizon and base measure independent of θ\theta:

pθ(τ)=exp⁡(θ⊤Φ(τ))Z(θ),Φ(τ)=∑t=0T−1ϕ(st).p_\theta(\tau)=\frac{\exp(\theta^\top\Phi(\tau))}{Z(\theta)},\qquad \Phi(\tau)=\sum_{t=0}^{T-1}\phi(s_t).

For NN trajectories, average log-likelihood is θ⊤μ^E−log⁡Z(θ)\theta^\top\widehat\mu_E-\log Z(\theta) up to a constant. Differentiating the log partition gives

∇θℓ=μ^E−Epθ[Φ(τ)].\nabla_\theta\ell=\widehat\mu_E-\mathbb E_{p_\theta}[\Phi(\tau)].

Reward rises for features more frequent in demonstrations and falls for those more frequent in the model. With stochastic dynamics, base measure and causal assumptions matter: arbitrarily normalizing impossible trajectories is insufficient. The causal-entropy version uses policies conditioned on available information. Ziebart and colleagues develop MaxEnt IRL.

In the lab’s deterministic grid, with state reward and temperature one, calculate backwards Qt(s,a)=r(s)+∑s′P(s′∣s,a)Vt+1(s′)Q_t(s,a)=r(s)+\sum_{s'}P(s'\mid s,a)V_{t+1}(s'), Vt(s)=log⁡∑aeQt(s,a)V_t(s)=\log\sum_a e^{Q_t(s,a)} and πt(a∣s)=eQt(s,a)−Vt(s)\pi_t(a\mid s)=e^{Q_t(s,a)-V_t(s)}. Stable log-sum-exp is used. Forward, dt+1(s′)=∑s,adt(s)πt(a∣s)P(s′∣s,a)d_{t+1}(s')=\sum_{s,a}d_t(s)\pi_t(a\mid s)P(s'\mid s,a) and expected frequency is ∑tdt\sum_t d_t. The policy depends on time remaining; a stationary discounted formula answers a different problem.

The second figure uses cell-indicator features and the exact occupancy gradient. Changing iterations or rate lets you observe convergence and oscillation. A reward constant adds the same amount to every fixed-length trajectory: the parameter mean is removed, but other ambiguities remain. The example expert is also a soft policy; if demonstrations were suboptimal or depended on unobserved variables, fitting could explain noise as preference.

One iteration is concrete: first convert current weights to reward, then the backward pass calculates a policy, the forward pass predicts visits, and finally compare them with the expert’s. Visits are expected counts summing to TT, not probabilities summing to one; division by TT only changes gradient scale. A cell unreachable from the start has zero frequency for both expert and model, so their data do not identify its weight. Descent in the figure depends on this small problem and rate; it is not a general guarantee for deep networks.

A GAN over occupancies

The occupancy measure ρπ(s,a)\rho_\pi(s,a) counts visits to state-action pairs with appropriate discounting and normalization. Generative adversarial imitation learning (GAIL) trains a discriminator D(s,a)D(s,a) to distinguish expert pairs from policy pairs, and adjusts the policy with RL using a signal derived from that discriminator. With convention D=P(experto)D=\Pr(\text{experto}), the discriminator objective is EE[log⁡D]+Eπ[log⁡(1−D)]\mathbb E_E[\log D]+\mathbb E_\pi[\log(1-D)]. At the optimal discriminator, D∗=ρE/(ρE+ρπ)D^*=\rho_E/(\rho_E+\rho_\pi); ideal comparison relates to Jensen-Shannon divergence between normalized occupancies. Ho and Ermon also include causal-entropy regularization and a dual relationship with IRL.

The third figure removes all dynamics: an action chooses one of 25 cells and frequencies are one-step occupancy. BC fits empirical frequencies; the adversarial version calculates the optimal discriminator and descends JS. With few demonstrations both can poorly reproduce unseen modes; the example does not prove neural implementations converge. In a sequential task, policy pairs come from new rollouts, so GAIL needs interactions; BC can train offline on saved pairs, though evaluating both requires interaction.

The optimal discriminator maximizes ρElog⁡D+ρπlog⁡(1−D)\rho_E\log D+\rho_\pi\log(1-D) separately for each pair. Substituting the ratio into the objective gives −log⁡4+2 JS⁡(ρE∥ρπ)-\log 4+2\,\operatorname{JS}(\rho_E\|\rho_\pi) when both measures are normalized. Matching occupancies is stronger than matching only aggregate features, but requires the discriminator to see relevant variables. If it receives only images, states with the same appearance and different velocities may be indistinguishable even when they require different actions.

A common signal is −log⁡(1−D)-\log(1-D), always nonnegative; another convention uses log⁡D\log D, nonpositive. In episodes with variable endings, the sign can reward survival or early termination independently of the task. Control the horizon, handle absorption and examine the signal. Changing the discriminator convention changes formulas too: check which class DD represents to avoid reversing training.

AIRL structures the discriminator with reward and potential terms to separate some dynamics modelling and favour transfer under additional assumptions; it does not guarantee recovery of a unique intention in every environment. See Fu, Luo and Levine. BC often dominates when many useful demonstrations exist and fitting actions is cheap. IRL can be valuable if interpretable reward and new dynamics permit replanning; GAIL avoids specifying explicit reward but pays for RL and simulation. RLHF preferences provide comparisons instead of expert actions: objective inference is analogous, not identical.

Lab: reward and transfer

The soft expert generates 300 demonstrations on one map. Two weights are inferred for known goal and hazard indicators; those indicators are then placed at new positions and planning is repeated. Tabular BC instead retains actions conditioned on position and time in the old map. This constructed comparison makes explicit the semantic knowledge enabling transfer and does not show every inferred reward transfers. Probabilities and returns are exactly calculated expectations, not invented rates.

[ ]MaxEnt IRL and a new mapBrowser
import numpy as np
N=5;S=N*N;A=4;H=14
def build(goal,hazard):
    P=np.zeros((S,A,S));moves=[(0,-1),(1,0),(0,1),(-1,0)]
    for s in range(S):
        x,y=s%N,s//N
        for a,(dx,dy) in enumerate(moves):
            sp=goal if s==goal else min(N-1,max(0,x+dx))+N*min(N-1,max(0,y+dy));P[s,a,sp]=1
    features=np.zeros((S,2));features[goal,0]=1;features[hazard,1]=1
    return P,features
def soft_policy(P,reward,horizon=H):
    S,A,_=P.shape;V=np.zeros((horizon+1,S));policy=np.zeros((horizon,S,A))
    for t in range(horizon-1,-1,-1):
        Q=reward[:,None]+np.einsum('sak,k->sa',P,V[t+1]);m=Q.max(axis=1,keepdims=True)
        V[t]=m[:,0]+np.log(np.exp(Q-m).sum(axis=1));policy[t]=np.exp(Q-V[t,:,None])
    return policy
def occupancy(P,policy,p0):
    d=p0.copy();visits=np.zeros_like(d)
    for pi in policy:
        visits+=d;d=np.einsum('s,sa,sak->k',d,pi,P)
    return visits,d
def sample(P,pi,p0,rng):
    s=int(rng.choice(S,p=p0));states=[];acts=[]
    for t in range(len(pi)):
        a=int(rng.choice(A,p=pi[t,s]));states.append(s);acts.append(a);s=int(rng.choice(S,p=P[s,a]))
    return np.array(states),np.array(acts),s
P,features=build(goal=24,hazard=12);p0=np.eye(S)[0];theta_true=np.array([1.4,-1.2]);expert=soft_policy(P,features@theta_true)
rng=np.random.default_rng(12);demos=[sample(P,expert,p0,rng) for _ in range(300)]
emp=np.mean([features[states].sum(axis=0) for states,acts,last in demos],axis=0)
theta=np.zeros(2)
for it in range(200):
    pi=soft_policy(P,features@theta);visits,_=occupancy(P,pi,p0);gradient=emp-features.T@visits;theta+=.2*gradient/H
print('características demostradas',np.round(emp,3),'theta aprendida',np.round(theta,3),'error de gradiente',round(np.linalg.norm(gradient),4))
# BC tabular con suavizado: una distribución por tiempo y estado.
counts=np.ones((H,S,A))*.05
for states,acts,last in demos:
    for t,(s,a) in enumerate(zip(states,acts)):counts[t,s,a]+=1
bc=counts/counts.sum(axis=2,keepdims=True)
Pnew,Fnew=build(goal=20,hazard=11);irl=soft_policy(Pnew,Fnew@theta);new_expert=soft_policy(Pnew,Fnew@theta_true)
for name,pi in [('BC',bc),('IRL',irl),('experto',new_expert)]:
    visits,final=occupancy(Pnew,pi,p0);true_return=float(theta_true@(Fnew.T@visits));print(name,'probabilidad de meta',round(final[20],3),'retorno verdadero esperado',round(true_return,3))
assert np.allclose(occupancy(P,expert,p0)[0].sum(),H)

Expert and inferred rewards can produce similar occupancies without matching every coefficient. The calculation uses finite samples for expert expectation, so the gradient does not vanish exactly after a fixed number of steps. Varying seed or demonstration count assesses that variation; information about which cell is goal or hazard is explicitly supplied on both maps.

Local lab: GAIL and BC in locomotion

Create an isolated environment with Python 3.10 or 3.11 and install pip install imitation==1.0.1 stable-baselines3==2.2.1 "gymnasium[mujoco]==0.29.1". The code trains a reference PPO policy from scratch in HalfCheetah, collects 25 episodes and compares BC and GAIL with 1, 5 and 25 fixed episodes. It does not assume PPO is expert: its return is printed before comparison. Each episode lasts at most 200 steps, avoiding comparison of fixed-sign rewards with different termination horizons.

For each count, labels, training interactions and mean and standard deviation of true return over ten common seeds are printed. Obtaining the reference policy and demonstrations also costs samples and is reported separately; BC has zero online training steps, while GAIL uses additional steps. One training seed, a small budget and ten episodes make results illustrative and noisy; they do not establish one method’s superiority.

[ ]Train and evaluate in HalfCheetahLocal GPU
import numpy as np
import torch
import gymnasium as gym
from stable_baselines3 import PPO
from stable_baselines3.common.vec_env import DummyVecEnv
from imitation.data import rollout
from imitation.data.wrappers import RolloutInfoWrapper
from imitation.algorithms import bc
from imitation.algorithms.adversarial.gail import GAIL
from imitation.rewards.reward_nets import BasicRewardNet

torch.set_num_threads(2)
SEED=12

def env(): return gym.make('HalfCheetah-v4', max_episode_steps=200)
def evaluate(policy):
    rewards=[]
    for seed in range(200,210):
        e=env(); obs,_=e.reset(seed=seed); total=0
        for _ in range(200):
            action,_=policy.predict(obs, deterministic=True)
            obs,r,terminated,truncated,_=e.step(action);total+=r
            if terminated or truncated:break
        rewards.append(total);e.close()
    return float(np.mean(rewards)),float(np.std(rewards,ddof=1))

v=DummyVecEnv([lambda:RolloutInfoWrapper(env())]);v.seed(SEED)
reference=PPO('MlpPolicy',v,n_steps=128,batch_size=64,n_epochs=3,seed=SEED,device='cpu',verbose=0)
reference.learn(200000)
print('Referencia PPO: pasos de entrenamiento',reference.num_timesteps,'retorno medio y desviación',evaluate(reference),flush=True)
trajectories=rollout.rollout(reference,v,rollout.make_sample_until(min_episodes=25),rng=np.random.default_rng(SEED))[:25]
print('Demostraciones:',len(trajectories),'transiciones',sum(len(t.acts) for t in trajectories),flush=True)
for n in (1,5,25):
    data=rollout.flatten_trajectories(trajectories[:n])
    trainer=bc.BC(observation_space=v.observation_space,action_space=v.action_space,demonstrations=data,rng=np.random.default_rng(SEED+n),batch_size=32)
    trainer.train(n_epochs=4,progress_bar=False,log_interval=100000)
    print('BC',n,'etiquetas',len(data.acts),'pasos online 0; retorno',evaluate(trainer.policy),flush=True)
    vg=DummyVecEnv([lambda:RolloutInfoWrapper(env())]);vg.seed(SEED+n)
    gen=PPO('MlpPolicy',vg,n_steps=128,batch_size=64,n_epochs=3,seed=SEED+n,device='cpu',verbose=0)
    reward=BasicRewardNet(vg.observation_space,vg.action_space)
    gail=GAIL(demonstrations=data,demo_batch_size=32,venv=vg,gen_algo=gen,reward_net=reward)
    gail.train(total_timesteps=4096)
    print('GAIL',n,'etiquetas',len(data.acts),'pasos online',gen.num_timesteps,'retorno',evaluate(gen),flush=True)
    vg.close()
v.close()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Practice

Proof
Prove: Derive the gradient of average trajectory log-likelihood.
0
Use p(τ) proportional to exp(θ·Φ(τ)) with a finite set and base measure independent of θ.

Step 1 of 3. What is the average log-likelihood up to constants?

Proof
Prove: Prove invariance under a potential transformation.
0
Infinite horizon, γ less than 1 and bounded Φ; compare policies from the same initial state.

Step 1 of 3. What remains after summing γᵗ(γΦ(sₜ₊₁)−Φ(sₜ)) through T−1?

Quiz
What does GAIL ideally match, and why does it require additional interaction?
Numeric
With D=0.8 as expert probability, calculate −log(1−D) using the natural logarithm.
Code
Implement soft_value_iteration(P, r, gamma) with P shaped (S,A,S), state reward and tolerance 1e-10, returning (V, policy). Implement expected_svf(P, policy, p0, T) as the sum of state distributions over T steps. Temperature one; 0≤gamma<1.
import numpy as np
def soft_value_iteration(P,r,gamma):
  pass
def expected_svf(P,policy,p0,T):
  pass
Shift+Enter to run
Key idea
Behaviour does not identify a unique reward; IRL and GAIL require assumptions and occupancy data, and their usefulness must be weighed against interaction cost.