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
- 24The imitation learning problemBehavior cloningCompounding error and the quadratic horizon boundDataset Aggregation
- 22Value iterationBellman optimality equationDiscounted occupancy measurePolicy gradient theoremPPO clipped objectiveMaximum entropy RL
- 07Maximum entropy principleGibbs distribution
- 05Exponential family
- 19GAN minimax gameOptimal discriminator
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.
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 , with and bounded potential. Its telescoping discounted sum is : 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 ; 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 . For a policy, summarizes visits. If 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 , Cauchy-Schwarz bounds the absolute return difference by . Scale 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 :
For trajectories, average log-likelihood is up to a constant. Differentiating the log partition gives
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 , and . Stable log-sum-exp is used. Forward, and expected frequency is . 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 , not probabilities summing to one; division by 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 counts visits to state-action pairs with appropriate discounting and normalization. Generative adversarial imitation learning (GAIL) trains a discriminator to distinguish expert pairs from policy pairs, and adjusts the policy with RL using a signal derived from that discriminator. With convention , the discriminator objective is . At the optimal discriminator, ; 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 separately for each pair. Substituting the ratio into the objective gives 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 , always nonnegative; another convention uses , 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 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.
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.
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()npm run lab and open the connection link.Practice
Step 1 of 3. What is the average log-likelihood up to constants?
Step 1 of 3. What remains after summing γᵗ(γΦ(sₜ₊₁)−Φ(sₜ)) through T−1?
import numpy as np
def soft_value_iteration(P,r,gamma):
pass
def expected_svf(P,policy,p0,T):
pass