Simple Algorithm
Reinforcement Learning · Bootstrapping · 22 min

Inverse RL & Reward Learning

Inferring the reward that explains observed behavior.

A taxi driver never states how she trades speed against distance and turns, yet her routes reveal it. Inverse reinforcement learning infers a reward from behavior. This lesson poses the problem precisely, derives Ng and Russell's characterization of the rewards that make a policy optimal, faces the ambiguity it exposes, builds the two ideas that tame it, feature matching and maximum entropy, and follows reward learning to comparisons, corrections and RLHF.

What you’ll learn

  • State the inverse RL problem, and derive Ng and Russell's linear conditions under which a given policy is optimal.
  • Explain reward ambiguity (degenerate rewards, scaling, potential-based shaping) and why behavior pins down at most an equivalence class of rewards.
  • Explain why matching feature expectations guarantees near-expert performance, and implement maximum-entropy IRL in a tabular MDP.
  • Describe reward learning from comparisons, corrections and other feedback as Boltzmann-rational choice, and its relation to RLHF.

The inverse problem

Forward RL takes an MDP (S,A,P,r,γ,μ)(\mathcal S,\mathcal A,P,r,\gamma,\mu) and finds an optimal policy. Inverse RL (Russell, 1998; Ng & Russell, 2000) runs the other way: given the MDP without its reward and observations of an expert's behavior, either its policy πE\pi^E or sampled demonstrations, find a reward function under which that behavior is optimal or nearly so. Three motivations recur:

  • Transfer. A reward is often a more compact and more portable description of a task than a policy: it can be re-optimized on a new map, with new dynamics or for new start states.
  • Understanding behavior. In economics, transportation and human–robot interaction the reward is the object of interest itself: what do drivers trade off, where is a pedestrian heading?
  • Specification. When a reward is hard to write down, as with a pleasant driving style, demonstrating the task specifies it indirectly.

Ng and Russell studied the cleanest case: finitely many states, actions a1,…,aka_1,\dots,a_k with transition matrices PaP_a, a reward R∈R∣S∣R\in\R^{\abs{\mathcal S}} that depends on the state only, γ∈(0,1)\gamma\in(0,1), and a fully known expert policy. Renaming the actions in each state, we may assume the expert always takes a1a_1.

DerivationProof
  1. Vπ=R+γPa1Vπ⟹Vπ=(I−γPa1)−1RV^\pi = R + \gamma P_{a_1}V^\pi\quad\Longrightarrow\quad V^\pi = \big(I - \gamma P_{a_1}\big)^{-1}R

    The policy's value solves its Bellman equation, and I−γPa1I - \gamma P_{a_1} is invertible for γ<1\gamma < 1 (Policy Evaluation as Linear Algebra):

  2. R+γPa1Vπ ⪰ R+γPaVπ⟺(Pa1−Pa)Vπ⪰0R + \gamma P_{a_1}V^\pi\ \succeq\ R + \gamma P_a V^\pi\quad\Longleftrightarrow\quad \big(P_{a_1} - P_a\big)V^\pi\succeq 0

    By the policy improvement theorem, π\pi is optimal exactly when it is greedy with respect to its own values: in every state, a1a_1 is at least as good as any aa. The immediate reward R(s)R(s) is the same for every action, and γ>0\gamma > 0, so this reduces to a comparison of expected next values:

  3. (Pa1−Pa)(I−γPa1)−1R⪰0for all a≠a1■\big(P_{a_1} - P_a\big)\big(I - \gamma P_{a_1}\big)^{-1}R\succeq 0\quad\text{for all }a\ne a_1\qquad\blacksquare

    Substitute VπV^\pi. Strict inequalities in every state mean no other action ties with a1a_1 anywhere, which is uniqueness.

Read the theorem as geometry. The rewards that make π\pi optimal form a polyhedral convex cone: linear inequalities in RR, closed under positive scaling and under addition. Ng and Russell immediately noted its embarrassment: R=0R = 0 satisfies every inequality, since under the zero reward every policy is optimal. So does every positive multiple of a solution, and the cone usually contains rewards with very different meanings.

One behavior, many rewards

This reward ambiguity has a clean structure. Three transformations never change which policies are optimal:

  • Positive scaling, r↦c rr\mapsto c\,r with c>0c > 0.
  • Adding a constant to every reward, in a continuing discounted task. (With terminal states it is not harmless: a constant changes how attractive it is to end the episode.)
  • Potential-based shaping (Ng, Harada & Russell, 1999; see Reward Shaping): for any Φ:S→R\Phi:\mathcal S\to\R, the reward r′(s,a,s′)=r(s,a,s′)+γΦ(s′)−Φ(s)r'(s,a,s') = r(s,a,s') + \gamma\Phi(s') - \Phi(s). Telescoping the shaping terms along any trajectory shifts every action value by the same state-dependent amount, Q′π(s,a)=Qπ(s,a)−Φ(s)Q'^\pi(s,a) = Q^\pi(s,a) - \Phi(s), so the ranking of actions in each state is unchanged, whatever the dynamics.

Beyond these, a demonstration only shows what the expert did where it went. It says little about states it never visited, and nothing about how much better its choices were than the alternatives. The widget below makes the second point concrete: the same reward, observed under two different dynamics, reveals different things.

Check your understanding

An inverse RL method returns a reward r^\hat r. You add γΦ(s′)−Φ(s)\gamma\Phi(s') - \Phi(s) to it for some arbitrary Φ\Phi. Which statement is true?

  1. The new reward makes different policies optimal unless Φ\Phi is constant
  2. The new reward explains the demonstrations exactly as well, in every environment with the same states, so no amount of demonstrations can determine Φ\Phi
  3. The new reward explains the demonstrations better, because it has more parameters
  4. The two rewards are identical
Show the answer

B. The new reward explains the demonstrations exactly as well, in every environment with the same states, so no amount of demonstrations can determine Φ\Phi

Potential-based shaping changes every action value in state ss by the same amount, −Φ(s)-\Phi(s), for every policy and every transition function, so the optimal policies, and with them any behavior generated from them, never change. Rewards learned from demonstrations of optimal behavior are at best determined up to such transformations, and up to much more when the expert is only observed in some states.

IRL algorithms therefore add a selection principle. Ng and Russell's first proposal was a margin: among rewards that make the expert optimal, with ∣R(s)∣≤Rmax⁡\abs{R(s)}\le R_{\max}, maximize the total gap between the expert's action and the best alternative, ∑smin⁡a≠a1[(Pa1(s)−Pa(s))(I−γPa1)−1R]\sum_s\min_{a\ne a_1}\big[(P_{a_1}(s) - P_a(s))(I - \gamma P_{a_1})^{-1}R\big], minus a penalty λ∥R∥1\lambda\norm{R}_1 that favors simple rewards. That is a linear program. The two principles that shaped the field came next.

Match features, not rewards

Suppose the reward is linear in known features, r(s)=w⊤ϕ(s)r(s) = \mathbf w^\top\boldsymbol\phi(s), with unknown weights. A policy's feature expectations μ(π)=Eπ[∑t≥0γtϕ(St)]\boldsymbol\mu(\pi) = \E_\pi\big[\sum_{t\ge0}\gamma^t\boldsymbol\phi(S_t)\big] determine its value for every such reward, Jw(π)=w⊤μ(π)J_{\mathbf w}(\pi) = \mathbf w^\top\boldsymbol\mu(\pi), by linearity of expectation. (Bold μ\boldsymbol\mu denotes feature expectations; the start distribution is still μ\mu.) Hence, by Cauchy–Schwarz,

∣Jw(π)−Jw(πE)∣≤∥w∥2 ∥μ(π)−μ(πE)∥2.\big|J_{\mathbf w}(\pi) - J_{\mathbf w}(\pi^E)\big| \le \norm{\mathbf w}_2\,\norm{\boldsymbol\mu(\pi) - \boldsymbol\mu(\pi^E)}_2 .

A learner that matches the expert's feature expectations is as good as the expert under every reward in the class, without ever identifying the true one. That is the idea of apprenticeship learning (Abbeel & Ng, 2004), developed in its own Fixed Point lesson.

Feature matching still leaves many policies, and many trajectory distributions, that match. Maximum-entropy IRL (Ziebart, Maas, Bagnell & Dey, 2008) picks the least committal one: among distributions over trajectories whose expected feature counts equal the expert's, take the one with maximum entropy. For deterministic dynamics that distribution is pw(τ)∝exp⁡(w⊤f(τ))p_{\mathbf w}(\tau)\propto\exp\big(\mathbf w^\top\mathbf f(\tau)\big) with f(τ)=∑tϕ(st)\mathbf f(\tau) = \sum_t\boldsymbol\phi(s_t): better trajectories are exponentially more likely, but none is impossible, which also makes the model tolerant of an imperfect expert. Fitting w\mathbf w by maximum likelihood has a famously simple gradient, the expert's feature counts minus the model's expected feature counts, computed by a backward pass (soft value iteration) and a forward pass (expected state visits).

python
import numpy as np

def maxent_irl(P, phi, demos, T, lr=0.1, iters=200):
    """P: (A, S, S) with P[a, s, s2] = P(s2 | s, a); phi: (S, k) state features;
    demos: list of integer arrays, each the T states of one demonstration."""
    A, S, _ = P.shape
    f_expert = np.mean([phi[traj].sum(axis=0) for traj in demos], axis=0)
    p0 = np.bincount([traj[0] for traj in demos], minlength=S) / len(demos)
    w = np.zeros(phi.shape[1])
    for _ in range(iters):
        r = phi @ w                               # state rewards
        V, policy = np.zeros(S), []
        for t in range(T - 1, -1, -1):            # backward pass: soft value iteration
            Q = r[None, :] + P @ V                # Q[a, s] = r(s) + E[V(s2)]
            V = np.logaddexp.reduce(Q, axis=0)    # soft maximum over actions
            policy.append(np.exp(Q - V[None, :])) # pi_t(a | s)
        policy = policy[::-1]
        D, f_model = p0.copy(), np.zeros_like(w)
        for t in range(T):                        # forward pass: expected visits
            f_model += D @ phi
            D = np.einsum('s,as,ast->t', D, policy[t], P)
        w += lr * (f_expert - f_model)            # log-likelihood gradient
    return w

Tabular maximum-entropy IRL over a finite horizon TT, undiscounted as in Ziebart et al. The soft backup averages over next states, which is the causal version of the model; for deterministic dynamics it coincides with the 2008 trajectory model. The Fixed Point lesson derives every line.

Other evidence about rewards

Demonstrations are one kind of evidence among many. People compare two behaviors, push a robot away from a vase, switch it off, or say what they want. Jeon, Milli and Dragan (2020) proposed one lens for all of them, reward-rational (implicit) choice. Each piece of feedback is a choice cc from a set of options C\mathcal C (two trajectories to compare, all demonstrations the person could have given, stopping the robot or letting it continue); a grounding function maps each option to the behavior it stands for; and the person chooses Boltzmann-rationally, with probability proportional to exp⁡(β×the reward of that behavior)\exp\big(\beta\times\text{the reward of that behavior}\big) for a rationality coefficient β\beta. Learning the reward is then maximum likelihood or Bayesian inference under one model, whatever the feedback.

P(τA≻τB)=eβR(τA)eβR(τA)+eβR(τB)=σ(β(R(τA)−R(τB)))P\big(\tau_A\succ\tau_B\big) = \frac{e^{\beta R(\tau_A)}}{e^{\beta R(\tau_A)} + e^{\beta R(\tau_B)}} = \sigma\Big(\beta\big(R(\tau_A) - R(\tau_B)\big)\Big)
For a comparison the choice set is {τA,τB}\{\tau_A,\tau_B\}, and the model is the Bradley–Terry model used to fit RLHF reward models. Choosing one demonstration among all feasible trajectories with probability ∝eβR(τ)\propto e^{\beta R(\tau)} is exactly the maximum-entropy IRL model.
Predict before you look

With β=1\beta = 1, trajectory A's return exceeds B's by 1. Under the Bradley–Terry model, how often does the labeler prefer A?

Show the answer

0.73

σ(1)=1/(1+e−1)≈0.731\sigma(1) = 1/(1+e^{-1})\approx0.731. A labeler who prefers the better trajectory only 73% of the time still carries information: the rate of agreement grows with the size of the difference, which is how comparisons reveal not only the order of rewards but their differences, provided the noise model is right.

Uses, limits and what comes next

Some representative uses:

  • Route choice. Ziebart et al. (2008) modeled Pittsburgh's road network as a deterministic MDP with over 300,000 states (road segments) and learned how 25 taxi drivers traded off road features from over 100,000 miles of GPS traces. The model predicted routes and inferred destinations from partly completed trips.
  • Driving and motion planning. Abbeel, Dolgov, Ng and Thrun (2008) learned the trade-offs of a robot car's parking-lot planner, such as forward versus reverse driving and staying on the road, from demonstrations; Kuderer, Gulati and Burgard (2015) learned individual drivers' styles with feature-based IRL, to make an autonomous car drive the way its passenger prefers.
  • Forecasting people. Kitani, Ziebart, Bagnell and Hebert (2012) extended maximum-entropy inverse optimal control to forecast pedestrians' paths and destinations from video.

Key takeaways

  • Inverse RL infers a reward under which observed behavior is (near-)optimal. In finite MDPs with state rewards, π≡a1\pi\equiv a_1 is optimal exactly when (Pa1−Pa)(I−γPa1)−1R⪰0(P_{a_1} - P_a)(I-\gamma P_{a_1})^{-1}R\succeq0 for all aa: a convex cone of rewards that always contains R=0R = 0.
  • Positive scaling, constant shifts (in continuing tasks) and potential-based shaping never change optimal policies, and demonstrations reveal nothing about states the expert never visits: behavior pins down at most an equivalence class of rewards.
  • Values are linear in feature expectations, so matching the expert's feature expectations guarantees expert-level performance for every reward in the class; maximum-entropy IRL selects the least committal model consistent with that match.
  • Comparisons, corrections, stops and demonstrations can all be modeled as Boltzmann-rational choices that reveal the reward; for comparisons this is the Bradley–Terry model behind RLHF's reward models.
  • Inverse RL depends on its model of the demonstrator and usually solves RL in its inner loop; with a wrong model of rationality, more data do not fix the inferred reward.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

In Ng and Russell's condition (Pa1−Pa)(I−γPa1)−1R⪰0(P_{a_1} - P_a)(I - \gamma P_{a_1})^{-1}R\succeq0, what does each component of the vector express?

  1. That the expert's action earns a larger immediate reward than aa in that state
  2. That in that state the expected value of the next state, under the values of following π\pi, is at least as large after a1a_1 as after aa
  3. That the reward is nonnegative in that state
  4. That a1a_1 is the most frequently demonstrated action in that state
Show the answer

B. That in that state the expected value of the next state, under the values of following π\pi, is at least as large after a1a_1 as after aa

(I−γPa1)−1R(I - \gamma P_{a_1})^{-1}R is VπV^\pi, and row ss of (Pa1−Pa)Vπ(P_{a_1} - P_a)V^\pi compares the expected next value after a1a_1 with that after aa. Since the reward depends only on the state, that comparison is exactly the policy improvement condition.

Question 2

Which reward always belongs to the set of rewards under which a given policy is optimal?

  1. The true reward of the task
  2. The reward that pays 1 for the expert's action and 0 otherwise
  3. The reward of maximum margin
  4. The zero reward
Show the answer

D. The zero reward

Under r≡0r\equiv0 every policy is optimal, so the zero reward satisfies every inequality of the cone. It is the starkest form of reward ambiguity, and the reason IRL needs a selection principle such as a margin or maximum entropy.

Question 3

A learner's feature expectations are within ϵ\epsilon of the expert's in Euclidean norm. What is guaranteed for every reward r=w⊤ϕr = \mathbf w^\top\boldsymbol\phi with ∥w∥2≤1\norm{\mathbf w}_2\le1?

  1. Nothing, unless the learner also recovers w\mathbf w
  2. The learner's value is within ϵ\epsilon of the expert's
  3. The learner's value is within ϵ/(1−γ)\epsilon/(1-\gamma) of the expert's
  4. The learner's policy equals the expert's
Show the answer

B. The learner's value is within ϵ\epsilon of the expert's

Values are linear in feature expectations, Jw(π)=w⊤μ(π)J_{\mathbf w}(\pi) = \mathbf w^\top\boldsymbol\mu(\pi), so Cauchy–Schwarz gives ∣Jw(π)−Jw(πE)∣≤∥w∥2 ϵ≤ϵ\abs{J_{\mathbf w}(\pi) - J_{\mathbf w}(\pi^E)}\le\norm{\mathbf w}_2\,\epsilon\le\epsilon. The discount is already inside μ\boldsymbol\mu.

Question 4

An RLHF reward model is fitted by maximizing the Bradley–Terry likelihood of human comparisons. In the reward-rational choice view, what is the person's choice set for one label?

  1. The two responses being compared
  2. Every response the model could ever produce
  3. The possible values of the reward
  4. The parameters of the language model
Show the answer

A. The two responses being compared

Each label is a choice between the two shown responses, made with probability proportional to eβRe^{\beta R} of each. Demonstrations are the case where the choice set is all feasible trajectories, which turns the same model into maximum-entropy IRL.

Question 5

Why can an IRL method infer a badly wrong reward even from unlimited, noise-free data?

  1. Because gradient methods cannot fit the maximum-entropy model exactly
  2. Because unlimited data always overfit the features
  3. Because it relies on a model of how the demonstrator chooses, and if the demonstrator is biased or plans differently, the data are best explained by a wrong reward
  4. Because rewards are only defined for optimal agents
Show the answer

C. Because it relies on a model of how the demonstrator chooses, and if the demonstrator is biased or plans differently, the data are best explained by a wrong reward

Behavior depends on the reward and on how the agent turns rewards into actions. A misspecified model of the second absorbs its errors into the first, and more data only make the wrong answer more certain. This is the core of Armstrong and Mindermann's argument.

Go deeper

Further reading

  • A. Y. Ng & S. Russell, "Algorithms for inverse reinforcement learning," ICML (2000).
  • P. Abbeel & A. Y. Ng, "Apprenticeship learning via inverse reinforcement learning," ICML (2004).
  • B. D. Ziebart, A. Maas, J. A. Bagnell & A. K. Dey, "Maximum entropy inverse reinforcement learning," AAAI (2008).
  • H. J. Jeon, S. Milli & A. D. Dragan, "Reward-rational (implicit) choice: A unifying formalism for reward learning," NeurIPS (2020).