Inverse RL and Adversarial Imitation (UC Berkeley CS 285)

Twenty expert paths cross a grid. Inverse RL finds a reward that makes them likely: here the log-likelihood of a demo climbs from −16.1 to about −5.0, and the reward still works when a wall appears.

Press Step. Purple rollouts come from the soft-optimal policy for the current reward. Then the reward rises where the teal demos go more often than the policy, and falls where they go less. Press Run to repeat, then switch the map to see other rewards that explain the same paths. Then we build it piece by piece: the likelihood, its gradient, importance weights, the GAN view and GAIL.

You need GAIL in one paragraph from Reward Learning and soft value iteration from Control as Inference. We build the rest here.

A supplement to UC Berkeley CS 185/285, Deep Reinforcement Learning, Sergey Levine. Sources: Lecture 13 (inverse RL and adversarial imitation), Lecture 14 (part 1), Section 7 and Lecture 22. The words, toys and numbers are our own.

Learn a reward from 20 paths

Illustrative toy: a 5×5 grid, 5 moves, 10 steps, one reward number per cell. The 20 demos are samples from a near-optimal policy for a goal and puddle reward. Each step solves soft value iteration exactly, draws 20 rollouts, and moves each cell by 0.5 × (expert visits − rollout visits).

Chapter 0

Copy the Intent, Not the Actions

See why a learned reward survives a changed world, and why many rewards explain the same paths

A person reaches for a cup with the left hand, because the right hand holds a phone. A robot that copies actions learns "use the left hand." A robot that copies intent learns "get the cup," and uses whichever hand is free.

Behavior cloning (BC) copies actions: it maps each state to the expert's action and never reasons about outcomes. Inverse reinforcement learning (IRL) infers the reward the expert seems to maximise, then runs RL on it. When the world changes, RL plans new actions for the same goal.

QuestionBehavior cloningInverse RL
What it learnsA map from state to actionA reward, then a policy from RL
A wall appearsWalks into the wallPlans around it
CostOne supervised fitRL inside a loop

Many rewards explain the same paths

Our demos are 20 paths in a 5×5 grid, from the bottom-left start to the top-right goal. Each takes 8 moves, steps around a 2×2 puddle, and then waits 2 steps at the goal. Which reward made them? Paint one and check.

Paint a reward that explains the demos

Tap a cell to cycle its reward: 0, then +1 (warm), then −1 (blue). The teal lines are the demos; the purple line is where a greedy agent goes on your reward.

Illustrative toy. A demo "is a best path" when its total reward over the 10 steps equals the best total any action sequence can get, found by dynamic programming. The greedy agent breaks ties by staying put.

Under "goal only", a demo arrives at step 8 and waits 2 steps, so it collects +1 three times: a total of 3, the best possible. Under "zero everywhere" every path totals 0, so every path is best, and the greedy agent never moves. The demos fit the useless reward perfectly.

So IRL by itself is underspecified: the demos do not pick one reward. The failure is a reward that fits the demos but trains an agent that idles. Measure it by running RL on the reward and comparing its visits with the demos. The fix is a model that asks for demos to be likely, not merely optimal: Chapter 1.

  1. The likelihood: the chance of a demo under a reward, and the partition function Z.
  2. The gradient: expert visits minus soft-optimal visits.
  3. Importance weights: guided cost learning, without a full RL run per step.
  4. IRL is a GAN: a discriminator built from the reward.
  5. GAIL: a plain classifier, and why it is the same thing.
  6. The field guide: numbers, code, links and the credit.
Every demo is a best path under a reward of 0 in every cell. What does this show?

Chapter 1

The Likelihood of a Demo, and the Partition Function

Score a reward by how likely it makes the demos, and meet the one term that is hard to compute

Control as inference gives a model of a near-optimal expert: a path is more likely the more reward it collects, in proportion to e to the reward. IRL uses that model backwards. Call the reward r-psi, a function with parameters ψ: 25 numbers here, one per cell, or the weights of a neural network.

p(τ | O, ψ) = p(τ) exp(rψ(τ)) ⁄ Z
Say it aloud

p of tau given O and psi equals p of tau, times e to the r-psi of tau, divided by Z.

p(τ | O, ψ)
p of tau given O and psi the chance of path tau, given that the expert acted optimally under reward psi.
p(τ)
p of tau the chance the dynamics allow the path: the start and every move. It is 1 for any action sequence in our grid.
exp(rψ(τ))
e to the r-psi of tau e raised to the path's total reward, summed over its 10 steps.
Z
Z the partition function: p of tau times e to the reward, added over every possible path.
In plain words

Raise e to each path's total reward. Divide by Z, the same number added over all paths, so the chances sum to 1.

With numbers

In our toy, 5 moves for 10 steps give 510 = 9,765,625 action sequences. With a reward of 0 everywhere, each has e0 = 1, so Z = 9,765,625 and each path has a chance of 1 in 9,765,625.

The best reward makes the demos most likely. Take the log of the chance of each demo, average over the N demos, and drop log p(τ), which does not depend on ψ.

L(ψ) = (1/N) Σi rψ(τi) − log Z
Say it aloud

L of psi equals one over N times the sum over i of r-psi of tau-i, minus log Z.

L(ψ)
L of psi the average log-likelihood of a demo under reward psi. Higher is better.
(1/N) Σi
one over N times the sum over i the average over the N demos; N is 20 here.
rψ(τi)
r-psi of tau-i the total reward of demo i.
log Z
log Z the log of the partition function. It grows when the reward also likes paths the demos skip.
In plain words

Add up the reward of each demo and average. Subtract log Z, so a reward cannot score well by loving every path.

With numbers

Take the goal and puddle reward at scale 1. Every demo totals 1.6, and log Z = 13.77, so L = 1.6 − 13.77 = −12.17. At scale 5 the demos total 8.0, log Z = 13.10, and L = −5.10: the demos are now much more likely.

Turn up the reward scale

Teal is the demos' average reward, purple is log Z, warm is L, their difference. Drag the scale, then add two wandering demos.

1.0

Illustrative toy. The reward is c times the goal and puddle shape. Log Z comes from soft value iteration, exact because we know the grid's moves. The two wanderers are 10-step paths that never reach the goal.

With clean demos, L levels off at −5.09 = −log 162. The model ends spread evenly over the 162 best action sequences: 18 routes that miss the puddle, times 9 ways to spend the last 2 steps at the goal. Add 2 wanderers and L peaks at c = 3.66: a noisy expert gets a gentler reward.

Why is log Z hard? It adds over every path: 10 million here, and an integral over paths with unknown dynamics for a real robot. Drop it and the failure is a reward that grows without limit, because the first term rises forever with c. Watch log Z, and estimate it from samples: Chapters 2 and 3.

Why does the objective subtract log Z instead of only maximising the demos' reward?

Chapter 2

The Gradient: Expert Samples Minus Soft-Optimal Samples

Differentiate log Z, find the soft-optimal policy inside it, and turn the gradient into visit counts

To climb L we need its gradient. The first term is easy: the average of the gradient of each demo's reward. For log Z, the gradient of a log is the gradient divided by the value. So the gradient of log Z is the sum over paths of p(τ) er ∇r, divided by Z.

That weight, p(τ) er / Z, is the model's own chance of each path from Chapter 1. It is the path distribution of the soft-optimal policy, the policy that max-entropy RL learns for the current reward.

∇ψL = Eτ~π*[∇ψrψ(τ)] − Eτ~p(τ|O,ψ)[∇ψrψ(τ)]
Say it aloud

The gradient of L with respect to psi equals the expected gradient of r-psi of tau over the expert's paths, minus the expected gradient of r-psi of tau over the soft-optimal paths.

∇ψL
the gradient of L with respect to psi the direction that raises the demos' likelihood fastest.
Eτ~π*[…]
the expected value over the expert's paths estimated by averaging over the demos.
Eτ~p(τ|O,ψ)[…]
the expected value over the soft-optimal paths estimated by averaging over rollouts of the soft-optimal policy for the current reward.
In plain words

Push the reward up along the demos. Push it down along the paths the current soft-optimal policy takes. When the two sets look alike, the pushes cancel.

With numbers

With one reward per cell, the gradient of a path's reward with respect to cell s is how often the path visits s. The next equation uses that.

Call the average visits to cell s by the demos μE(s), and by the soft-optimal policy μψ(s).

∂L ⁄ ∂r(s) = μE(s) − μψ(s)
Say it aloud

The partial of L with respect to r of s equals mu-E of s minus mu-psi of s.

∂L ⁄ ∂r(s)
the partial of L with respect to r of s how much L rises per unit of reward added to cell s.
μE(s)
mu-E of s average visits to cell s per demo, over the 10 steps.
μψ(s)
mu-psi of s average visits to cell s per rollout of the soft-optimal policy.
In plain words

For each cell, count how often the demos visit it and how often the policy visits it. The difference is that cell's gradient.

With numbers

At step 0 the reward is 0, so the policy wanders. At the goal, μE = 3.0 and μψ = 0.002, so the gradient is 3.00 and a step of size 0.5 adds 1.50. At the start corner, μE = 0 and μψ = 2.75, so its reward drops by 1.37.

Subtract the policy's visits from the expert's

Left: demo visits. Middle: soft-optimal policy visits. Right: their difference, the gradient. Pick a point in training.

Illustrative toy. Here the policy visits are exact expectations from soft value iteration, and each step adds 0.5 × the gradient. The hero uses 20 sampled rollouts instead, as the course does.

This is the course's first algorithm. With a linear reward on features it becomes the feature matching of the CMU IRL lesson.

  1. Run max-entropy RL with rψ until it converges.
  2. Sample paths from that policy.
  3. Take one gradient step on ψ with the demos and the samples.
  4. Go back to step 1.

The failure is cost: a whole RL run for every reward step. The symptom is a loop that spends all its time in step 1. Measure the RL steps per reward step. The fix is Chapter 3.

A cell gets 0.4 visits per demo and 1.1 visits per rollout of the soft-optimal policy. What does one gradient step do to its reward?

Chapter 3

Lazy Policy Updates and Importance Weights

Improve the policy a little per round, and reweight its samples so the gradient stays honest

Instead of training the policy to convergence, improve it a little each round. Now the samples come from the current policy π, not from the soft-optimal one, so the second term is biased. Importance weights fix that: each sample counts in proportion to how much more likely the target makes it than π does.

wj = exp(Σt rψ(st, at)) ⁄ ∏t π(at | st)
Say it aloud

w-j equals e to the sum over t of r-psi of s-t and a-t, divided by the product over t of pi of a-t given s-t.

wj
w-j the importance weight of sample path j.
exp(Σt rψ)
e to the sum over t of r-psi e to the path's total reward: the target's chance, up to Z.
∏t π(at | st)
the product over t of pi of a-t given s-t the chance the current policy picks each action of the path.
In plain words

The full ratio is p(τ) er over p(τ) times the policy's action chances. The start and the dynamics appear on top and bottom, so they cancel. Only the reward and the policy remain.

With numbers

With made-up numbers: a 2-step path earns rewards 0.5 and 1.0, and the policy chose its actions with chances 0.4 and 0.5. Then w = e1.5 / (0.4 × 0.5) = 4.48 / 0.2 = 22.4.

∇ψL ≈ (1/N) Σi ∇ψrψ(τi) − (1/Σjwj) Σj wj ∇ψrψ(τj)
Say it aloud

The gradient of L is about one over N times the sum over i of the gradient of r-psi of tau-i, minus one over the sum of the w-j, times the sum over j of w-j times the gradient of r-psi of tau-j.

∇ψL
the gradient of L the same target as Chapter 2.
(1/N) Σi …
one over N times the sum over i the demo term: a plain average over N demos.
(1/Σjwj) Σj wj …
one over the sum of the w-j, times the sum over j of w-j a weighted average over the M policy samples. Dividing by the weights' sum cancels the unknown Z.
In plain words

Turn the weights into shares that add to 1. Average the policy samples by those shares, not equally.

With numbers

With made-up numbers: three samples have weights 22.4, 11.2 and 5.6, so the shares are 0.571, 0.286 and 0.143. They visit a cell 1, 0 and 2 times. The weighted count is 0.571 + 0 + 0.286 = 0.86; the plain average is 1.00.

Let the policy go stale

Yellow bars are the 200 samples' shares, largest first. Drag how many reward steps pass without a policy update.

8

Illustrative toy. The policy is soft-optimal for the reward after 2 training steps; 200 rollouts come from it with a fixed seed. Error is the summed gap, over 25 cells, to the exact visits of the soft-optimal policy for the newer reward.

After 8 stale steps, the plain average is off by 3.13 visits and the weighted one by 0.68. But the weights also concentrate: the effective sample size, (Σw)² / Σw², falls from 200 to 100. That is the failure to watch. If it nears 1, one sample decides the gradient; the fix is to update the policy more often.

Guided cost learning (Finn et al., 2016) is this loop with a neural reward:

  1. Generate samples from the policy π.
  2. Update the reward with the demos and the weighted samples.
  3. Update π a little on the new reward, then repeat.
Why can guided cost learning compute wj without knowing the environment's dynamics?

Chapter 4

IRL Is a GAN

Read the loop as a game, then build the discriminator from the reward so the weights disappear

Look at the loop of Chapter 3. The reward step makes demos more likely and policy samples less likely. The policy step makes the samples harder to tell from the demos. That is a game: the policy is the generator and the reward is the discriminator, as in a GAN.

A GAN's discriminator D(x) is a classifier that gives the chance that x is real. Call the real data's density p* and the generator's pθ.

D*(x) = p*(x) ⁄ (pθ(x) + p*(x))
Say it aloud

D-star of x equals p-star of x, divided by p-theta of x plus p-star of x.

D*(x)
D-star of x the best discriminator's chance that x is real.
p*(x)
p-star of x how densely the real data (the demos) covers x.
pθ(x)
p-theta of x how densely the generator (the policy) covers x.
p*(x)
p-star of x again, so the two shares add to 1.
In plain words

At each x, D-star is the real data's share of the total density.

With numbers

With made-up densities p* = 0.3 and pθ = 0.1, D* = 0.3 / 0.4 = 0.75. When the generator matches the data, D* = 0.5.

Finn, Christiano and colleagues put the reward inside D. In IRL, the policy should end at p(τ) er / Z, so use that in place of p*. The policy's path chance is p(τ) ∏πθ, and p(τ) cancels from top and bottom.

Dψ(τ) = (1/Z) exp(rψ(τ)) ⁄ (∏t πθ(at | st) + (1/Z) exp(rψ(τ)))
Say it aloud

D-psi of tau equals one over Z times e to the r-psi of tau, divided by the product over t of pi-theta of a-t given s-t, plus one over Z times e to the r-psi of tau.

Dψ(τ)
D-psi of tau the discriminator's chance that path tau is a demo.
(1/Z) exp(rψ(τ))
one over Z times e to the r-psi of tau the reward model's chance of the path. Z is one more number, trained with psi.
∏t πθ(at | st)
the product over t of pi-theta of a-t given s-t the current policy's chance of the path's actions.
(1/Z) exp(rψ(τ))
one over Z times e to the r-psi of tau again, as in the GAN formula.
In plain words

Compare the reward model's chance of the path with the policy's chance. D is the reward's share. Train ψ and Z with the usual GAN loss: log D on demos plus log(1 − D) on policy samples.

With numbers

With made-up numbers: the reward model gives a path 0.02 and the policy gives it 0.005. Then D = 0.02 / 0.025 = 0.8. Once the policy also gives 0.02, D = 0.5.

Train the policy, watch D

Pink bars are D for four paths, under the learned reward. Drag the policy from uniform toward soft-optimal.

0.40

Illustrative toy. The reward is the one IRL learns in 60 exact steps. The policy at setting λ is soft-optimal for λ times that reward, so λ = 0 is uniform and λ = 1 matches the reward model. Z is exact.

No importance weights appear. The ratio inside D does their job, and Z absorbs the normalising sum. The failure to watch is the usual GAN imbalance: D near 1 on every demo and near 0 on every sample from the first round. Measure the mean D on each side; fix it with fewer reward steps per policy step.

The policy becomes soft-optimal for the learned reward. What does Dψ output on any path?

Chapter 5

GAIL: A Plain Classifier, and Why It Is the Same Thing

Swap the reward-shaped discriminator for any classifier, see what you lose, and find the reward hiding in D

Reward Learning met GAIL (Ho and Ermon, 2016): D is a standard binary classifier, and the policy uses log D as its reward. Here is the policy step.

∇θL ≈ (1/M) Σj ∇θ log πθ(τj) log Dψ(τj)
Say it aloud

The gradient of L with respect to theta is about one over M times the sum over j of the gradient of log pi-theta of tau-j, times log D-psi of tau-j.

∇θL
the gradient with respect to theta the direction that improves the policy's parameters theta.
(1/M) Σj
one over M times the sum over j the average over M policy samples.
∇θ log πθ(τj)
the gradient of log pi-theta of tau-j the direction that makes path j more likely.
log Dψ(τj)
log D-psi of tau-j the reward: near 0 for a path that looks like a demo, far below 0 otherwise.
In plain words

This is the policy gradient with log D in place of the return. Paths that fool D get pushed up more.

With numbers

With made-up numbers: D = 0.8 gives log D = −0.22, and D = 0.2 gives −1.61. So the second path gets about 7 times the push down.

DiscriminatorGainLoss
Plain classifier (GAIL)Simpler to set up, fewer moving partsAt convergence D = 0.5 everywhere, so the "reward" cannot be reused
Reward-shaped (IRL as a GAN)A reward rψ survives trainingNeeds the policy's action chances inside D

The course calls the two "actually the same thing." Take the log-odds of the IRL discriminator from Chapter 4.

log Dψ − log(1 − Dψ) = rψ(τ) − log Z − Σt log πθ(at | st)
Say it aloud

Log D-psi minus log of one minus D-psi equals r-psi of tau, minus log Z, minus the sum over t of log pi-theta of a-t given s-t.

log D − log(1 − D)
log D minus log of one minus D the log-odds that the path is a demo.
rψ(τ)
r-psi of tau the path's learned reward.
log Z
log Z one constant, the same for every path.
Σt log πθ
the sum over t of log pi-theta the log-chance the policy gives the path's actions.
In plain words

Divide D by 1 − D: the policy terms cancel except one. Use this log-odds as the policy's reward and average over its own paths. You get reward plus entropy, minus a constant: max-entropy RL on rψ.

With numbers

From Chapter 4: D = 0.8 gives log(0.8 / 0.2) = log 4 = 1.39. The right side is log(0.02 / 0.005) = log 4 = 1.39 too.

Change the world, reuse what was learned

Pick a world and what to plan with. Lines are 16 rollouts; green ends at the goal, red does not.

Illustrative toy. IRL reward: the 60-step learned reward, re-solved by soft value iteration in the new world. GAIL's final D: 0.5 on every state, as at convergence, so log D is flat. Copied actions: the demos' most common action per state, random where they never went. Success is exact.

Add the wall. The learned reward re-plans around it and reaches the goal 99.5% of the time; copied actions walk into the wall, 0%. GAIL's converged classifier says 0.5 everywhere, so its policy wanders: 0%. That is the failure of reusing a GAIL reward. Measure it by checking whether D varies over states. The fix is a reward-shaped D, or training GAIL again in the new world.

Why can the IRL-as-GAN reward be reused in a new world when GAIL's final classifier cannot?

Chapter 6

The Field Guide

Keep the equations, the numbers, a checklist and the core loop on one page, and see where to go next

Maximum entropy IRL models the expert as soft-optimal: a path's chance grows as e to its reward. The best reward maximises the demos' log-likelihood. Its gradient is expert visits minus soft-optimal visits. Guided cost learning replaces the inner RL run with a lazy policy and importance weights. Put the reward inside a GAN discriminator and the weights vanish into Z. GAIL drops the reward shape for a plain classifier: simpler, but nothing reusable remains.

The equations

IdeaFormChapter
Expert modelp(τ|O,ψ) = p(τ) erψ(τ) / Z1
ObjectiveL = mean of rψ(demos) − log Z1
GradientEexpert[∇r] − Esoft-optimal[∇r]2
Importance weightw = eΣr / ∏π(a|s)3
IRL discriminatorD = (er/Z) / (∏π + er/Z)4
GAIL policy rewardlog D from a plain classifier5
Same thinglog-odds of D = r − log Z − Σ log π5

The numbers from our toy

WhatNumberWhy it matters
Paths in the grid510 = 9,765,625Z adds over all of them
Demo log-likelihood−16.09 at reward 0; about −4.98 after 60 stepsWhat IRL climbs
Clean demos, any scaleL levels at −log 162 = −5.09Perfect demos push the reward scale up without end
Two wanderers addedBest scale 3.66, L = −6.43Noise gives a finite reward
First gradient at the goal3.0 − 0.002 = 3.00Expert visits minus policy visits
8 stale steps, 200 samplesError 3.13 plain, 0.68 weighted; ESS 100Weights remove bias but cost samples
Wall addedIRL 99.5%, copied actions 0%, GAIL's final D 0%Only a reward transfers

Checklist

  1. Check the demos: are they near-optimal, and from which states?
  2. Choose the reward's inputs: states only, or states and actions.
  3. Track log Z or its sample estimate. A reward that grows without limit means it is missing.
  4. With lazy updates, weight the samples and log the effective sample size.
  5. For a reusable reward, use the reward-shaped discriminator, not a plain classifier.
  6. Test the reward by re-running RL in a changed world.

The core loop

pythonimport numpy as np

def irl_step(r, demo_visits, policy, sample, lr=0.5, M=20):
    # r: (S,) one reward per state; demo_visits: (S,) mean visits per demo
    paths = [sample(policy) for _ in range(M)]           # each: (states, actions, logp)
    logw = np.array([r[s].sum() - logp for s, a, logp in paths])
    w = np.exp(logw - logw.max()); w /= w.sum()          # self-normalised: Z cancels
    pol_visits = np.zeros_like(r)
    for wj, (s, a, logp) in zip(w, paths):
        np.add.at(pol_visits, s, wj)                     # weighted visit counts
    ess = 1.0 / (w ** 2).sum()                         # watch this
    return r + lr * (demo_visits - pol_visits), ess

# outer loop: r, ess = irl_step(...); then improve policy a little on r (any max-ent RL)

Keep going

The takeaway. IRL asks which reward makes the demos likely. The answer climbs a gradient of expert visits minus soft-optimal visits, and only a reward, not a classifier, still works when the world changes.
Which part of maximum entropy IRL forces an RL problem inside the loop?

Now press Present or Teach and explain from memory: the likelihood, why log Z is hard, the gradient as visit counts, the weights, the GAN discriminator and what GAIL gives up. Then go back to the hero, train the reward, and switch the maps.

Credit and source

This lesson supplements UC Berkeley CS 185/285, Deep Reinforcement Learning, Sergey Levine, at rail.eecs.berkeley.edu/deeprlcourse. It draws on Lecture 13 (pages 17 to 34), Lecture 14 (pages 2 to 12), Section 7 (pages 1 to 2) and Lecture 22 (pages 30 to 33). The papers are Finn, Levine and Abbeel, Guided Cost Learning (2016); Finn, Christiano, Abbeel and Levine, A Connection Between GANs, Inverse RL, and Energy-Based Models (2016); and Ho and Ermon, Generative Adversarial Imitation Learning (2016). The words, toys and numbers here are our own.

Inverse RL and Adversarial Imitation (UC Berkeley CS 285)
The course site · Lecture 13 PDF · Section 7 PDF · Back to Gleams