Inverse Reinforcement Learning

Nobody can write the reward for careful driving, but a careful driver can show it. Inverse RL reads the reward out of the demos. Then it plans with that reward where the demos never went, and there copying the actions fails.

Pick a learner, then pick a test. Watch which one reaches the goal dry from a new start and on a new map. Then we build, piece by piece, why many rewards fit the same demos, how feature counts pin them down, and how maximum entropy picks one.

You need reward, policy and return (Lecture 5) and a little Python. No IRL assumed. We build the rest from zero.

Lecture 18 of 25 in Introduction to Robot Learning, CMU 16-831 (Spring 2024), taught by Guanya Shi. Slides on the course lectures page. Every idea is re-taught here in our own words and devices. Next: Lecture 19, Bandits and Preference Learning.

Test two learners on the same demos

Illustrative 9 by 6 grid. The expert plans with a hidden reward per cell entered (road −0.2, grass −1, water −5, goal +5) and gives 3 demos. The copier stores the demo actions and, off the demos, copies the nearest demo cell. The inverse-RL learner runs 400 steps of MaxEnt IRL (Chapter 8) on the demos, then plans with what it found.

Chapter 0

The Reward You Cannot Write Down

Try to write the reward for a careful driver, and find out why examples are easier

Your team wants a delivery robot that drives the way a careful person does. Reinforcement learning needs a reward: a number the robot gets at each step and tries to make large over the whole trip. So someone must write that number down.

Try it. How much worse is grass than road? Is wading through a puddle worth two steps saved? Each weight is a guess, and the guesses interact. Be that engineer below.

Write the reward by hand

The blue dots are a careful expert's path. The teal line is the best path for your reward. Grass costs 1 per cell and the goal pays 5. Set the other two costs.

1.00
1.0

Illustrative toy. The planner finds the path with the largest total reward within 22 steps. The planner subtracts a cost each time the robot enters a cell.

A first guess of "every cell costs 1" sends the robot through the pond. Many settings give the expert's path, and many do not. You can only check a guess by watching what it does.

You do have one thing: demonstrations, recordings of a careful person doing the task. The person never said their reward. They drove.

The problem. Reinforcement learning takes a reward and finds a policy. Inverse reinforcement learning (IRL) runs the arrow backward: it takes an expert's demonstrations and finds a reward the expert appears to maximize. Then ordinary RL plans with that reward, also where the expert never went.

The lecture places IRL in the family of learning from demonstrations:

The demos areUseReward needed?
Good (an expert)Imitation learning, including IRLNo: IRL recovers one
Mixed qualityOffline RL (Lecture 17)Yes, given

The failure, as symptom, measurement and fix

The symptom is a robot that games a hand-written reward: it finds a path the engineer did not foresee. To measure it, roll out the best policy for your reward from many starts and count the paths an expert would reject. The fix in this lecture is to learn the reward from the expert's own paths.

The road

  1. Copy or recover: what each learner stores, and why one survives a new map (the hero's two learners).
  2. Ambiguity: many rewards fit the same demos.
  3. Features: a reward as a few weights, a policy as one vector.
  4. Feature matching: match the counts and you match the value.
  5. The widest margin: the first tie-breaker, and how noise breaks it.
  6. Maximum entropy: a probability over paths that assumes nothing extra.
  7. The gradient: expert counts minus model counts.
  8. The loop: MaxEnt IRL running on the grid (the hero's reward).
  9. The field guide: terms, numbers, code, links and credit.
You cannot write a reward for "drive politely". What does IRL give you that ordinary RL does not?

Chapter 1

Copy the Actions or Recover the Intent

Store a lookup table or store four numbers, and see which one survives a new map

Both learners start from the same data: expert trajectories, lists of the states the expert visited and the actions it took there. They differ in what they keep.

Behaviour cloning (BC) treats imitation as supervised learning: state in, action out. It fits a policy π(a | s) to the expert's actions and never asks why. Off the expert's states it must guess, and Lecture 6 showed how those guesses compound.

IRL assumes the expert acts optimally for some hidden reward, and looks for that reward. Call a policy π, the hidden reward r-star, and the state and action at step t s-t and a-t. Call the discount γ, a number below 1 that shrinks late rewards.

Say it aloud

Pi-star equals the arg-max over pi of the expected value, under pi, of the sum over t of gamma to the t times r-star of s-t and a-t.

π*
pi-star the expert's policy. We see it only through its demos.
argmaxπ
the arg-max over pi the policy that makes what follows largest.
Eπ
the expected value under pi the average over many runs of policy π.
Σt
the sum over t one term for each step of a run.
γt
gamma to the t the discount, for example 0.9 multiplied by itself t times.
r*(st, at)
r-star of s-t and a-t the hidden reward for that step. This is what IRL looks for.
In plain words

Score every policy by its average discounted reward under r-star. The expert's policy pi-star must score highest. IRL searches for an r-star that makes this true.

With numbers

With made-up numbers: under a candidate reward, the expert's path is worth 3.44 and a shortcut through the water is worth −1.69. The expert wins, so the candidate fits this demo. IRL would rule out a candidate under which the shortcut won.

Compare what each learner stores

Each cell shows the learner's first move from there. A green dot means it reaches the goal dry from that cell; a red dot means it fails. Switch the learner, then move to the new map.

Same toy, demos and learners as the hero. Solid purple arrows are moves the copier saw in a demo; faint ones copy the move of the nearest demo cell.

The lecture states the bet behind IRL: learning the reward r-star is assumed to be statistically easier than learning the policy π-star. A reward is short. A policy must say what to do in every state.

Behaviour cloningInverse RL
Learnsa policy π(a | s)a reward r(s), then a policy by RL
New states, new mapsguessesplans again with the reward
Can you read it?no, a table or a networkyes, a few weights
Computeone supervised fitan RL solve per reward guess

The failure, as symptom, measurement and fix

The symptom is a cloned policy that works on the training map and fails when the goal moves. To measure it, test from starts and maps outside the demos, as the device does. The fix is to learn what the demos were for, then plan.

The demos come from one map. On a new map with the goal in another corner, why does the IRL learner reach the goal while the copier does not?

Chapter 2

Many Rewards Fit the Same Demos

Swap the reward map and watch the best moves stay where they are

The lecture names the trouble first: IRL is ill-posed. A set of demos does not fix one reward. Infinitely many rewards explain it, in three layers.

  1. The zero reward. If r = 0 everywhere, every policy earns 0. So the expert is optimal, and so is a policy that drives into a wall. The zero reward fits every demo and says nothing.
  2. Different shapes, same best moves. A spike at the goal, a slope toward it and the spike times 3 make the same moves best.
  3. Different mixes, same statistics. Later we summarize the expert by how often it visits each kind of state. Many mixtures of policies give the same counts (Ziebart and colleagues, 2008).

Swap the reward, keep the moves

Yellow shows the reward in each cell. Purple arrows show every best first move. Pick a reward and compare the arrows with the spike's.

Illustrative 7 by 4 grid, discount 0.9, the goal ends the run. Spike: +10 at the goal. Slope: +10 at the goal and minus the distance to it elsewhere.

Why does the scale not matter? Multiply every reward by a number c above 0, and every return grows by the same factor c. The ranking of policies stays the same. So demos can never tell you the scale of a reward.

The lab below makes the second layer literal on a corridor: two weight vectors, two reward curves, one greedy policy.

The fix is a tie-breaker: a rule that prefers one reward among all that fit. The lecture has two. The widest margin is Chapter 5. Maximum entropy is Chapters 6 to 8.

The failure, as symptom, measurement and fix

The symptom is an IRL run that returns a reward near zero and calls it a fit. To measure it, check that the reward ranks the expert above a bad policy by a clear gap. The fix is to rule out the empty answer, for example by fixing the length of the weight vector.

Why is the reward r = 0 for every state always a fit for the demos, and always useless?

Chapter 3

A Reward Made of Features

Turn the reward into a few weights, and sum up a whole policy as one vector

To make IRL solvable, the classical methods make one choice: the reward is a weighted sum of features. A feature is a number you can measure about a state. For a driver it is the gap to the car ahead. For our grid it is "is this cell road?" and "is this cell water?".

Call the list of features of a state s the vector φ(s). Call the unknown weights θ, one weight per feature.

Say it aloud

R-theta of s equals theta transpose phi of s.

rθ(s)
r-theta of s the reward for entering state s, under weights θ.
θ
theta the weights IRL looks for, one per feature.
T
transpose here: multiply matching entries and add them up (a dot product).
φ(s)
phi of s the feature vector of s, for example (1, 0) for a road cell and (0, 1) for water.
In plain words

Read the features phi of s of the cell. Multiply each one by its weight in theta. Add. That sum is the cell's reward r-theta of s.

With numbers

With made-up numbers: θ = (1, −2) for (road, water). A road cell has φ = (1, 0), so its reward is 1. A water cell has φ = (0, 1), so its reward is −2.

IRL now looks for a few numbers, not a whole function. φ can come from a neural network. The weights on top stay linear, and the maths below needs nothing more.

Next, sum up a policy by the features it collects. Call the discount γ and the state at step t s-t.

Say it aloud

Mu-pi equals the expected value, under pi, of the sum over t of gamma to the t times phi of s-t.

μπ
mu-pi the expected feature counts of policy π: one number per feature.
Eπ
the expected value under pi the average over many runs of π.
Σt
the sum over t one term per step.
γt
gamma to the t the discount: 0.9 to the power t here.
φ(st)
phi of s-t the features of the state at step t.
In plain words

Walk the path. At step t, take the cell's features phi of s-t and multiply them by gamma to the t. Add over the steps. Average over many runs. The result is mu-pi.

With numbers

With made-up numbers and γ = 0.9: a 4-step all-road path has road count 1 + 0.9 + 0.81 + 0.729 = 3.439 and water count 0, so μ = (3.439, 0). A shortcut of road, water, water, road has μ = (1 + 0.729, 0.9 + 0.81) = (1.729, 1.71).

Weigh two paths by their features

Each cell's reward is θ times its features, shrunk by 0.9 per step. Move the weights and watch which path is worth more.

1.0
−2.0

Illustrative numbers, γ = 0.9. The totals are V = θ·μ, the identity of Chapter 4.

From data, the expert's counts are an average over its m demos: μ-E ≈ (1/m) times the sum over demos of each demo's discounted feature sum. That one vector is the expert's fingerprint.

The failure, as symptom, measurement and fix

The symptom is a recovered reward that ignores something the expert cared about. The cause is a missing feature: if no feature says "a child is near", no weight can care about it. To measure it, look for demo choices that no feature explains. The fix is to add the feature.

With θ = (1, −2) for (road, water) and γ = 0.9, what is the reward of step 2 on a water cell, counted from the start?

Chapter 4

Match the Expert's Feature Counts

Move the learner onto the expert and watch the value gap close for every reward at once

Join the two equations. The value of a policy is its average discounted reward. Put r-theta = θ times φ inside it. θ does not change with time, so it moves out of the average and the sum.

Say it aloud

V-pi equals theta transpose mu-pi.

Vπ
V-pi the value of policy π: its average discounted reward from the start.
θT
theta transpose the reward weights, laid out to dot with mu-pi.
μπ
mu-pi the expected feature counts of π (Chapter 3).
In plain words

To score a policy under any linear reward, take its feature counts mu-pi, multiply each by its weight in theta, and add. The result is V-pi.

With numbers

With θ = (1, −2): the road path has μ = (3.439, 0), so V = 3.439. The shortcut has μ = (1.729, 1.71), so V = 1.729 − 3.42 = −1.691.

Abbeel and Ng (2004) drew the key consequence. Compare the expert E with a learner L. Their value gap is the weights dotted with their feature-count gap.

Say it aloud

The size of V-E minus V-L equals the size of theta transpose times mu-E minus mu-L, which is at most the length of theta times the length of mu-E minus mu-L.

|VE − VL|
the size of V-E minus V-L how far apart the expert's and the learner's values are, ignoring the sign.
θT
theta transpose any reward weights, including the true ones.
μE − μL
mu-E minus mu-L the feature-count gap: expert counts minus learner counts.
≤
is at most the left side never goes above the right side.
‖θ‖
the length of theta the square root of the sum of its squared entries.
In plain words

Take the feature-count gap mu-E minus mu-L. Its length times the length of theta caps the value gap. If the count gap is zero, the value gap is zero for every theta, the true one included.

With numbers

With made-up numbers: μ-E = (3.439, 0) and μ-L = (3.0, 0.5). The gap is (0.439, −0.5), length 0.665. Under θ = (1, −2) the value gap is 0.439 + 1.0 = 1.439. The cap is 2.236 × 0.665 = 1.488.

Move the learner onto the expert

Blue is the expert's counts, purple the learner's. The ring shows the value gap under every reward direction of length 1. Slide the learner until the ring shrinks to a point.

3.00
0.50

Illustrative counts. The "true" reward here is θ = (1, −2), length 2.236. The ring's radius in each direction is the gap under that unit-length θ.

This gives IRL a target that needs no θ: the feature-matching residual, the length of μ-E minus μ-L. Drive it to zero and the learner is as good as the expert under every linear reward. The lecture calls feature matching necessary and sufficient.

The failure, as symptom, measurement and fix

The symptom is a residual that will not go to zero. Either the learner's policies cannot reach the expert's counts, or the features miss something. To measure it, plot the residual feature by feature. The fix is a richer policy class or a better feature set.

Abbeel and Ng show that matching the expert's feature counts is sufficient. Sufficient for what?

Chapter 5

Win by the Widest Margin

Turn the reward until the expert beats every rival by the most, then add noise and watch it fail

Feature matching says what to reach. It does not say which θ to report. The lecture's first tie-breakers came before maximum entropy.

LP-IRL (Ng and Russell, 2000) picks the θ that makes the expert beat other policies by as much as possible. Value is linear in θ, so this is a linear program, a problem standard solvers handle fast. Each weight needs a bound such as |θ-i| ≤ 1, or the gap grows without end.

Max-margin IRL, also called apprenticeship learning (Abbeel and Ng, 2004), borrows the idea of a support vector machine. Call the rival policies π, each with feature counts μ-pi. Look for the weights of length at most 1 under which the expert's smallest lead is largest.

Say it aloud

The max over theta of length at most one, of the min over pi, of theta transpose times mu-E minus mu-pi.

max‖θ‖≤1
the max over theta of length at most one try every reward direction and keep the best. The length limit stops the scale from growing.
minπ
the min over pi the expert's lead over its closest rival: the margin.
θT
theta transpose the reward weights under test.
μE
mu-E the expert's feature counts.
μπ
mu-pi a rival policy's feature counts.
In plain words

Fix a direction theta. For each rival pi, compute the expert's lead, theta dotted with mu-E minus mu-pi. Keep the smallest lead. Turn theta until that smallest lead is largest.

With numbers

With made-up counts (road, water): expert (3.44, 0); rivals A (1.73, 1.71), B (2.20, 0), C (3.00, 0.50). At θ = (0.87, −0.50) the leads are 2.34, 1.07 and 0.63, so the margin is 0.63. The best direction is θ = (0.66, −0.75), with margin 0.67.

Turn the reward for the widest margin

The yellow arrow is the reward direction θ. Each dot's lead is how far the expert sits ahead of it along that arrow. Turn θ, then switch on noisy demos.

−30°

Illustrative counts. With noisy demos, 40% of the expert's runs take shortcut A, so the expert's counts move to (2.76, 0.68).

Where do the rivals come from? You make them: solve RL for the current θ, add that policy to the pool, then solve for θ again. This loop is the skeleton of every method in this lecture. Later work by Abbeel, Coates and Ng used apprenticeship learning to fly helicopter aerobatics from a pilot's demos.

The failure, as symptom, measurement and fix

Real demos are noisy. If 40% of the demos take the shortcut, the expert's counts move inside the rivals' region. Now every direction leaves the expert behind some rival: the best margin is −0.035. Measure it as a best margin at or below zero. The fix is a model of behaviour that expects mistakes: maximum entropy.

Max-margin IRL takes which idea from support vector machines, and when does it break?

Chapter 6

Assume Nothing Extra: Maximum Entropy

Tilt a probability over paths just enough to match the expert, and no more

Many rewards, and many probabilities over paths, still match the expert's counts. Maximum-entropy IRL (Ziebart, Maas, Bagnell and Dey, 2008, at CMU) picks one with a rule from information theory.

Entropy measures how spread out a probability distribution is: minus the sum of p times log p. The maximum-entropy principle (Jaynes, 1957) says: of all distributions that fit what you know, pick the most spread out. It assumes nothing you were not told. The lecture calls it Occam's razor.

A die shows it. If you know only that it has six faces, the answer is 1/6 each. If you also know the average roll is 4.5, maximum entropy tilts the faces just enough: 0.054, 0.079, 0.114, 0.165, 0.240 and 0.347. Each face up multiplies the probability by the same factor, about 1.45.

Ziebart applied this to whole paths. Call a path ζ (zeta), its feature total φ-zeta (the features of every state on it, added), and the weights θ. Maximize entropy, subject to matching the expert's feature totals. The answer has one form.

Say it aloud

P of zeta given theta equals e to the theta transpose phi-zeta, divided by Z of theta.

P(ζ | θ)
P of zeta given theta the probability that the expert takes path ζ, if its reward has weights θ.
exp
e to the turns a reward into a positive weight that grows fast as the reward grows.
θTφζ
theta transpose phi-zeta the total reward of path ζ.
Z(θ)
Z of theta the partition function: the sum of e to the reward over all paths, so the probabilities add to 1.
In plain words

Give each path zeta the weight e to its total reward. Add all the weights: that is Z of theta. Divide each path's weight by Z of theta.

With numbers

With made-up numbers: three paths with feature totals 1, 2 and 3, and θ = 1. The weights are 2.718, 7.389 and 20.086, so Z = 30.193. The probabilities are 0.090, 0.245 and 0.665. The best path is likely, not certain.

Tilt the path probabilities

Five candidate paths, each with a feature total. Slide θ from 0 upward and watch the probability pile onto the best path without ever taking all of it.

0.00

Illustrative feature totals 0.5, 1, 2, 2 and 3. The meter shows entropy as a share of its largest possible value, log 5.

This models the expert as noisily rational. Better paths are exponentially more likely, equal paths are equally likely, and a mistake keeps some probability. That is the noise tolerance max-margin lacked. θ also acts as a rationality dial: θ = 0 is a random walker, and a large θ is a perfect planner.

The failure, as symptom, measurement and fix

The symptom is a Z that nobody can compute by listing paths: it sums over every one. Our small grid with 4 moves and 20 steps has 4 to the 20, about 1012, move sequences. To measure it, count the paths before you list them. The fix is Ziebart's dynamic program: a backward pass and a forward pass over states (Chapter 8).

Among all path distributions that match the expert's feature totals, MaxEnt IRL picks which one?

Chapter 7

Fit the Reward by Gradient Ascent

Step θ along expert counts minus model counts, and watch the gap close or fail to

MaxEnt turns IRL into maximum likelihood: choose θ so the demos are as probable as possible. Call the average log-probability of the demos L(θ). With the form above it is θ times the expert's average feature total, minus log Z(θ). Its slope has a simple form.

Say it aloud

The gradient of L with respect to theta equals mu-E minus the expected value of phi-zeta, over paths zeta drawn from P given theta.

∇θL(θ)
the gradient of L with respect to theta the direction to move θ that raises the demos' log-probability fastest.
μE
mu-E the expert's average feature total over the demos.
Eζ~P(·|θ)[φζ]
the expected phi-zeta under P given theta the model's average feature total, if paths come from the current model.
In plain words

Compute the expert's feature totals mu-E. Compute the totals the current model expects. Subtract the model's from the expert's. Move theta a small step in that direction.

With numbers

With made-up numbers: five demos, three on path 3 and two on path 2, so μ-E = 2.6. At θ = 0 the model is uniform and expects 2.0, so the gradient is 0.6. A step of size 0.5 gives θ = 0.3, where the model expects 2.197.

Why this form: the slope of log Z(θ) is the sum over paths of e to the reward times φ-zeta, divided by Z. That is the model's average φ-zeta.

Step the reward toward the demos

The blue line is the expert's total μ-E. The pink curve is what the model expects after each step. Choose the demos, then step or run.

3 of 5

Illustrative: three paths with totals 1, 2 and 3; the other demos took path 2. Step size 0.5, starting at θ = 0.

Keep stepping. The gradient shrinks, 0.403 then 0.279 then 0.200, and θ settles at 1.06. There the model expects 2.6 and gives the paths 0.082, 0.236 and 0.682. The fixed point is feature matching, reached with the most spread-out distribution.

The failure, as symptom, measurement and fix

Put all five demos on path 3. Now μ-E = 3, the largest total possible. The model expects 3 only if all its mass is on path 3, which needs an infinite θ. The gradient stays positive and θ never settles. Measure it as a θ that keeps growing while the residual creeps down. The fix is more varied demos or a penalty on the size of θ.

The lab takes one step from θ = 1 in exactly that one-demo case.

Paths have totals 1, 2 and 3. At θ = 1 the model expects 2.575, and the demos average 2.6. What does one gradient step do?

Chapter 8

The IRL Loop, Running

Run MaxEnt IRL on the grid, add a noisy demo, and test the reward on a new map

Everything now joins into one loop. Each pass costs one RL solve, which is why IRL is expensive.

  1. Guess the weights θ. Start at 0.
  2. Solve for the model's path distribution under r-theta. A backward pass computes soft values; a forward pass spreads the start probability through the soft policy.
  3. Compare counts: the residual μ-E minus μ-theta, one entry per feature.
  4. Update θ along the residual, then go back to step 2.

θ ← θ + η (μE − μθ): the new theta is the old theta plus eta, the step size, times the residual.

Run the IRL loop

Blue dots are the demos. The yellow shading is the recovered reward per cell. The bars compare expert counts with the model's counts per feature. Run it, add the noisy demo, then test on the new map.

0.10

Same toy as the hero: horizon 22 steps, features road, grass, water and goal. On the new map, the teal paths are plans with the recovered reward from 4 sample starts.

Run it with the three clean demos. The residual falls from 13.9 to 0.06 in 400 passes. The weights come out road −3.06, grass −6.88, water −8.20 and goal +0.65. The hidden reward was −0.2, −1, −5 and +5. The numbers differ, the order is the same, and so are the plans: Chapter 2's ambiguity, live.

Add the noisy demo, which wades through three water cells. MaxEnt does not break. The water weight rises to −4.59, still the lowest, and the residual reaches 0.001 in 400 passes. A model that expects mistakes absorbs one.

The failure, as symptom, measurement and fix

Test the clean reward on the new map. From 4 of 49 starts, the plan crosses two water cells. The demos avoided water by a step or two, so the learned water penalty is only a little worse than grass. To measure it, test the reward on maps with new layouts. The fix is demos that pay for a long detour around water.

The link to GAIL (Lecture 6). The loop is a game: a learner makes behaviour, a comparison scores it against the expert, and the reward moves to separate them. GAIL (Ho and Ermon, 2016) makes the game explicit. A discriminator learns to tell expert state-action pairs from the learner's, and its output is the reward for a policy-gradient step. GAIL alternates one discriminator step with one policy step, so it never solves RL to the end inside the loop.
In the loop, what signal moves the reward weights?

Chapter 9

The Field Guide

Keep the terms and numbers, the methods side by side, a checklist and MaxEnt IRL in code

IRL reads a reward out of good demos, then plans with it. Many rewards fit, so every method adds a tie-breaker. With a linear reward, the demos enter only through their feature counts. Maximum entropy turns the search into a gradient: expert counts minus model counts.

Terms and numbers

TermOne lineNumber to remember
IRLFind r-star so the expert's policy is the arg-max of expected discounted reward.New map: copier 0 of 49 starts, IRL 45 of 49
Ill-posedMany rewards fit; r = 0 fits all.Slope vs spike: 27 cells differ, 0 moves differ
Linear rewardr-theta of s = θ dotted with φ(s).θ (1, −2): road 1, water −2
Feature countsμ-pi = average of the sum of γ to the t times φ(s-t).4 road steps: 3.439
Value identityV-pi = θ dotted with μ-pi.Road 3.439, shortcut −1.691
Feature matchingValue gap at most the length of θ times the count gap.1.439 ≤ 1.488
Max marginMaximize the expert's smallest lead with θ of length 1.0.67 clean, −0.035 with 40% noise
MaxEnt pathsP(ζ) = e to the reward over Z.Totals 1, 2, 3 at θ 1: 0.090, 0.245, 0.665
MaxEnt gradientμ-E minus the model's expected total.μ-E 2.6: θ settles at 1.06

The methods side by side

MethodTie-breakerNoisy demos?
LP-IRL (Ng and Russell, 2000)largest lead of the expert, as a linear programpoorly
Max margin (Abbeel and Ng, 2004)largest smallest lead, θ of length 1poorly
MaxEnt IRL (Ziebart et al., 2008)most spread-out path distributionwell
GAIL (Ho and Ermon, 2016)a discriminator as the reward, adversarialwell; no full RL solve per step

Before you trust a recovered reward

  1. Do the features cover what the expert cares about? A missing feature cannot get a weight.
  2. Does the reward rank the expert clearly above a bad policy? Rule out the zero reward.
  3. Does the residual go to zero? If not, check the policy class and the features.
  4. Does θ keep growing? Your demos may be too uniform; add variety or a penalty on θ.
  5. Plan with the reward on new starts and new maps. Compare plans, not weights.

MaxEnt IRL in code

pythonimport numpy as np

def maxent_irl(nxt, phi, goal, demos, T=22, iters=400, lr=0.1):
    """nxt[s, a] = next state; phi[s] = features of s; demos = lists of states."""
    S, A = nxt.shape
    mu_E = np.mean([phi[np.array(d[1:])].sum(0) for d in demos], axis=0)
    starts = [d[0] for d in demos]
    theta = np.zeros(phi.shape[1])
    for _ in range(iters):
        r = phi @ theta                          # reward for entering each state
        V, pis = np.zeros(S), []
        for t in range(T):                       # backward pass: soft values
            Q = r[nxt] + np.where(nxt == goal, 0.0, V[nxt])
            Vn = np.logaddexp.reduce(Q, axis=1); Vn[goal] = 0.0
            pis.append(np.exp(Q - Vn[:, None])); V = Vn
        pis = pis[::-1]
        d = np.bincount(starts, minlength=S) / len(starts)
        mu = np.zeros_like(theta)
        for t in range(T):                       # forward pass: expected visits
            flow = d[:, None] * pis[t]; flow[goal] = 0.0
            nd = np.bincount(nxt.ravel(), flow.ravel(), minlength=S)
            mu += nd @ phi; nd[goal] += d[goal]; d = nd
        theta += lr * (mu_E - mu)                # expert counts minus model counts
    return theta

On the grid of Chapter 8 with the three clean demos, this returns the same weights as the device: (−3.06, −6.88, −8.20, 0.65).

Keep going on this site

The takeaway. When you can show good behaviour but not score it, recover the reward, break the tie with maximum entropy, and test the reward by planning where the demos never went.

This lesson follows Lecture 18, Inverse Reinforcement Learning, of CMU 16-831 Introduction to Robot Learning, Spring 2024, taught by Guanya Shi. The slides are on the lectures page. The methods are from Ng and Russell (2000), Abbeel and Ng (2004), Ziebart, Maas, Bagnell and Dey (2008) and Ho and Ermon (2016). The grid, the paths and their numbers are our own toys.

Now press Present or Teach and explain from memory. Why is IRL ill-posed? Why does matching feature counts match value? Why is the MaxEnt gradient expert counts minus model counts? Then go back to the two learners, pick the new map, and say why only one arrives.

Introduction to Robot Learning · CMU 16-831 · Lecture 18: Inverse Reinforcement Learning
Next: Bandits and Preference Learning · Back to Gleams