Only differences of scores matter, so the scores are shown centred at 0.
Introduction to Reinforcement LearningPart 4 · Beyond value functions
Lecture 12Learning from people
When people provide the signal: imitation learning, behaviour cloning and DAgger, inverse RL and maximum entropy, learning from comparisons with the Bradley–Terry model, reinforcement learning from human feedback, and its limits.
Key ideas, one per episode
- Ep. 47Showing can be easier than explaining.
- Ep. 48Match the expert, and commit to nothing else.
- Ep. 49Comparisons are cheap; Bradley–Terry turns them into scores.
- Ep. 50Learn a reward from people, then optimise it on a leash.
- Ep. 51Learning from humans is hard, which makes it interesting.
Based on: Lecture 8: Imitation Learning and RLHF, Stanford CS234 (Spring 2024), by Emma Brunskill, with material from Tatsu Hashimoto’s CS224N lecture and Katerina Fragkiadaki’s lecture on maximum-entropy inverse RL. The slides follow that order of topics, in our own words, figures and examples; they are not official material of the original course.
Watch
5 short episodes of ACML Explains for this lecture. Pick one from the list, and open the transcript to read along: each timestamp plays the episode from there. The narration is generated with a voice clone of Teddy, used with his permission.
Episode 47 · 5:18
Learning from demonstrations
Write a reward for driving well. Go on, I'll wait.
Showing can be easier than explaining.
TranscriptEpisode 47
Write a reward for driving
Module twelve, the last one: learning from humans. Let's start with a challenge. Write me a reward for driving well. Go on, I'll wait. Stay in the lane. Don't hit anything. Don't brake too hard. Be polite at roundabouts. Every rule you add, an agent will find a loophole in. But any decent driver can just show you. One drive, and you see more than ten pages of rules.
Imitation learning
That's imitation learning. It's useful when demonstrating the behaviour is easier than writing the reward, or writing the policy directly. Driving. Tying a surgical knot. Folding a shirt. Ask an expert for a formula, and you get a shrug. Ask them to do it, and you get a demonstration. So the input changes. We still have states and actions. Sometimes we know the dynamics, sometimes not. But there is no reward at all. Instead, we get demonstrations: sequences of states and actions, from an expert's policy, pi star.
Three questions
From there, three questions. First, behaviour cloning: can we learn the expert's policy directly, with supervised learning? Second, inverse reinforcement learning: can we recover the reward the expert was optimising? Third, apprenticeship learning: can we use that reward to find a good policy of our own?
Behaviour cloning
Behaviour cloning first, because it's the simplest. Every state the expert visited is an input. The action they took is the label. Train a classifier. Done. This is the moment in the course where the supervised learning people finally relax. And it doesn't need the dynamics model. You never ask what happens next. You only ask what the expert did here. Mathematically: take every state and action pair from the demonstrations, and minimise the usual classification loss. Nothing in it knows about time. It works surprisingly often. And it fails in a very specific, very sneaky way.
Compounding errors
The expert is good. So the expert almost never makes mistakes. Which means the data never shows how to recover from one. Imagine learning to drive only from videos of perfect drivers. You've never seen anyone fix a drift. So the first time you drift, you're on your own. The copy makes one small error, and lands in a state the expert never visited. There, it has no idea what to do, so it makes a bigger error. And another. In supervised learning, the test data comes from the same place as the training data. Here, the copy chooses its own test data, by driving. People call this compounding errors, or distribution shift. A tiny error rate per step can add up to a big mess over a long drive.
Our lane toy
We tried it. A road nine cells wide. Gusts of wind push the car left or right, fifteen percent of the time each. The expert always steers back toward the centre. In twenty demonstrations, it never left the middle three cells. Our copy follows a table built from those demonstrations. But five percent of the time it picks a random action. And where it has no data at all, it acts at random. Two thousand drives of two hundred steps each. The expert went off the road zero times. The copy, in thirty seven percent of the drives. And look where the copy spent its last moments: in cells the expert never visited, with nothing to copy.
DAgger
The fix has a nice name: DAgger. Dataset aggregation, Ross, Gordon and Bagnell, twenty eleven. Let the copy drive. Every state it visits, ask the expert: what would you have done here? Add those answers to the data, and train again. Now the data includes the copy's own mistakes, with the right correction attached. In our toy, after one round, the copy went off the road in two drives out of a thousand. Ross and colleagues also showed why it matters. For behaviour cloning, the cost of small mistakes can grow with the square of the horizon. With DAgger, roughly linearly. The price: the expert has to sit in the passenger seat, for every round. Experts are expensive, and they get bored.
Inverse RL
Inverse reinforcement learning takes the other road. Don't copy the actions. Figure out what the expert wanted. Why? A reward transfers. New car, new road, new weather: the actions change, but the goal of not dying stays the same. A classic idea is feature matching, from Abbeel and Ng, two thousand four. Describe each state with features: speed, distance to the car ahead, lane position. If your policy visits those features as often as the expert does, you earn about the same reward. For any reward built from those features, with bounded weights. But there's a catch. Infinitely many rewards share the same optimal policy. Give zero reward everywhere, and every policy is optimal. Which reward should we pick? And the third question, apprenticeship learning, is the easy part. Once you have a reward, any method from this course can find a policy for
Recap
it. So: imitation learning, for when showing is easier than explaining. Behaviour cloning is simple, but it drifts. DAgger fixes the drift, at the price of a patient expert. Inverse RL looks for the reward instead. Next time: of all the rewards that could explain the expert, pick the least surprised one. Maximum entropy.
Many rewards, one principle
Last time, a problem. Many rewards explain the same expert. We need a principle to pick one. Here's one, from Edwin Jaynes, nineteen fifty seven. The principle of maximum entropy. Among all the distributions that agree with what you know, pick the one with the largest entropy. Commit to nothing you don't actually know. Think of a detective with too many suspects. You need a rule for choosing, or you end up accusing
Entropy
everybody. Entropy, quickly. Minus the sum of p times log p. It measures how spread out, how uncommitted, a distribution is. Someone hands you a die and tells you nothing. What's your honest guess? One sixth for each face. That's the maximum entropy distribution. Any other guess says: I know something about this die. And you don't. Claiming knowledge you don't have is how you lose money at the market. A coin that always lands heads has entropy zero. No surprise at all. A fair coin has the most entropy a coin can have.
A loaded die
Now add one fact. The average roll of this die is four and a half. Not three and a half. So it's loaded. But how, exactly? Many distributions have that average. Maximum entropy picks one, and its shape is always the same: exponential in the face value. We computed it. Five percent for a one, eight for a two, eleven, seventeen, twenty four, and thirty five percent for a six. Tilted, but nothing ruled out. Why not put all the weight on fours and fives? Because nothing told you a one is impossible. Maximum entropy only bends as far as the facts force
Trajectories
it to. Ziebart and colleagues, two thousand eight, did the same for trajectories. What we know: the expert's demonstrations, summarised by their features. The maximum entropy answer: the probability of a trajectory is proportional to e to the power of its reward. Better trajectories are exponentially more likely. But no trajectory is impossible. The expert is assumed to be good, and a little noisy. Just like real experts. Remember softmax policies from module ten? Same exponential, one level up. Over whole trajectories, instead of single actions. Two paths with the same reward get the same probability. The expert has no favourite between them, so neither do we.
The gradient
How do we find the reward? Make the demonstrations as likely as possible under this distribution. Maximum likelihood. For a linear reward, that's the same problem as maximum entropy, constrained to match the expert's feature counts. Two roads, one answer. And the gradient is beautiful. How often the expert visits each state, minus how often my current policy visits it. More of what the expert does. Less of what I do and the expert doesn't. I wish my own habits had a gradient this simple. Notice what the gradient doesn't need: the expert's exact actions. Only where the expert went, and how often.
The algorithm
The algorithm, then. Start with some reward. Compute the best soft policy for it, for example with value iteration. Compute how often that policy visits each state. Take one gradient step on the reward. Repeat. A check for you: which steps need the dynamics model? Computing the policy, and computing the visit frequencies. Behaviour cloning, remember, needed neither. In a big world, computing those visit frequencies exactly is expensive. That's one reason later methods sample instead.
Our grid
Our run. A five by five grid, a goal in one corner, and a small lake of lava in the middle. Thirty demonstrations from an expert that walks around it. The learner sees only the paths. Nobody tells it about the lava. It learns one reward per cell. Three hundred updates. The gap between its visit counts and the expert's shrank from fifteen point six to zero point one eight. Its policy reaches the goal in almost every run. It still steps on lava in about five percent of runs, because a maximum entropy policy stays a little noisy. The expert never did. And the learned reward? It looks like the true one, but not exactly. A correlation of about point eight. Many rewards explain the same paths, remember.
Beyond
The original method assumed two things: a reward that's linear in the features, and a known dynamics model. Finn and colleagues, twenty sixteen, removed both. General reward functions, learned while the robot acts, without knowing the dynamics in advance. And Ho and Ermon, twenty sixteen, went further: generative adversarial imitation learning. A critic tries to tell the expert from the learner. The learner tries to fool it. It's a lot like the adversarial networks that generate fake photos. Only here, the fakes are behaviour. Imitation can cut the data you need by a lot. And combining it with online reinforcement learning is still a very open, very exciting area.
Recap
So: when many rewards fit, pick the least committed distribution that still matches the expert. Trajectories become exponentially likely in their reward. The gradient matches visit counts. And the learned reward explains the behaviour, without being unique. Next time: what if the human doesn't demonstrate at all? What if they just say which of two things they like better?
Kinds of feedback
Humans can help an agent learn in many ways. Demonstrations are only one of them. A person can hand out rewards while the agent acts, like a clicker for a dog. Knox and Stone's TAMER framework learns a model of those human rewards. Thomaz and Breazeal, two thousand eight, watched people teach a robot. People didn't only reward the past. They used rewards to guide what the robot should do next. People can also correct an action, give advice, or compare two attempts. Each kind of feedback costs a different amount of human effort. Each kind also carries different information. A demonstration shows what to do. A correction shows what not to do, and what instead. A comparison only says: better, or worse.
The effort line
Put them on a line. At one end, constant teaching, like DAgger: an expert labels everything the agent does, round after round. At the other end, demonstrations only. The expert shows a few examples, and goes home. Somewhere in between: pairwise labels. Show the person two things, and ask which one is better. Maybe that's the sweet spot. And remember: the more effort each label costs, the fewer labels you'll get. Experts have day jobs.
Why pairs
Why pairs? Try this. How much do you like this advertisement, on a scale from one to ten? Ask me to rate a pizza from one to ten, I'll say seven. Every pizza is a seven. Put two pizzas in front of me, and suddenly I have very strong opinions. Absolute ratings are noisy, and every person uses the scale differently. Comparisons are easier to give, and much more consistent. Another bonus: comparisons don't care whether someone is generous or strict with numbers. Everybody's better means better.
Bradley–Terry
To learn from comparisons, we need a model of how people choose. The classic is Bradley and Terry, nineteen fifty two. Every option has a hidden score, r. To get the probability that a person prefers option i over option j, raise e to each score, and take i's share of the total. Equivalently, a sigmoid of the difference in scores. Same family as the softmax, again. Equal scores: a coin flip. A big gap: almost always the better one. Two consequences. Only differences matter, so add the same number to every score and nothing changes. And the model is transitive: one score per option means a clean ranking. Think of chess ratings. The rating difference between two players tells you how likely one is to beat the other. Same spirit.
Who wins?
What does it mean to win, with noisy comparisons? There are a few answers. A Condorcet winner beats every other option more than half the time. A Copeland winner has the most head-to-head wins. A Borda winner has the best average score against everyone. In a Bradley-Terry world, the option with the highest score is all three at once. Real preferences don't always cooperate. We'll see why in a minute. Which winner do we want? It depends on the application. Historically, algorithms for dueling bandits mostly looked for the Copeland winner.
Fitting the scores
Fitting the scores is just maximum likelihood. Each comparison is a small classification problem: did i win, or did j? The loss is the cross-entropy between what the person said and what the model predicted. Logistic regression, on differences in scores. With enough comparisons, of enough different pairs, the fitted scores approach the hidden ones. Two options that are never connected by any chain of comparisons? Their gap can't be learned. Each comparison nudges the winner's score up and the loser's down. More when the result was a surprise, less when it was expected.
Our five options
Our run. Five options, with hidden scores. A simulated person compares random pairs, and picks according to Bradley and Terry. After twenty comparisons, the fitted ranking is wrong. The best option isn't even on top. Twenty noisy answers are not much. After two hundred, the ranking is exactly right. After two thousand, the fitted scores are close to the hidden ones. The largest error, on the top option, is about a tenth of a point.
A cycle
Now a person with a cycle. Rock beats scissors, scissors beats paper, paper beats rock. Each preference holds ninety percent of the time. We fitted Bradley and Terry to twelve hundred of these comparisons. All three scores came out at about zero. So the model predicts a coin flip for every pair. The truth is ninety ten, every time. One score per option simply can't hold a cycle. Do real people have cycles? Ask anyone choosing a restaurant with friends. And it gets worse when you combine many people's preferences. Hold that thought for the last episode.
Recap
So: humans can help in many ways, at different costs. Pairwise comparisons are cheap and consistent, and Bradley and Terry turn them into scores. The same idea works for whole trajectories. The score of a trajectory is the sum of its rewards. Ask which of two trajectories is better, and fit the rewards. That gives us a reward model, learned from comparisons. And once you have a reward model, you know what to do next. Next time: reinforcement learning from human feedback. From robots doing backflips, to chatbots.
A reward model
Last time, we learned a reward model from comparisons. Now let's use it. Two trajectories. Each has a sum of rewards that nobody wrote down. The probability that a person prefers the first is a sigmoid of the difference between the two sums. Fit the reward model so it agrees with the people. Then forget about the people for a moment, and run reinforcement learning on the learned reward. For example, with PPO. In other words: the people teach the reward model, and the reward model teaches the agent. The agent never talks to a person directly.
The backflip
The classic demonstration: Christiano and colleagues, twenty seventeen. A simulated robot learns to do a backflip. Try writing a reward for a backflip. Height? Rotation speed? Landing on your feet, not your face? Good luck. Instead, a person watched pairs of short clips and picked the one that looked more like a backflip. About nine hundred pieces of feedback, and the robot flipped. The robot didn't need to understand backflips. It needed a reward model that agreed with the person often enough. Nine hundred clicks. I've spent more clicks choosing a laptop.
Three stages
Now the famous one: language models. The recipe has three stages. Stage one: pretrain a big model to predict the next word, on a lot of text. Stage two: instruction tuning. Fine-tune it on demonstrations of good answers. Stage three: collect comparisons. The model writes several answers to the same prompt, and people rank them. Fit a reward model. Then optimise the language model against it. Notice the old friends. Stage two is behaviour cloning. Stage three is Bradley and Terry, and then a policy gradient method. And stage one alone gives you a model that continues text. Ask it a question, and it might answer with three more questions.
The reward model
Why rank answers instead of scoring them? Because human judgements are noisy and miscalibrated. One person's seven is another person's four. The loss: minus the log of the sigmoid of the winner's reward minus the loser's. Push the winner up, push the loser down. And a piece of advice from the summarisation work of Stiennon and colleagues, twenty twenty: make sure your reward model works first. Test it on held-out human judgements. In their experiments, a large enough reward model, trained on enough comparisons, approached the agreement of a single human labeller. The reward model itself is often a copy of the language model, with a new head that outputs a single number.
On a leash
The RL step maximises the learned reward, minus beta times the log ratio between the new policy and the pretrained one. That second term is a price for wandering away from the original model. In expectation, it's the KL divergence between the two. Why pay that price? The reward model was trained on answers the original model writes. Far from those answers, nobody checked it. Keep beta in mind. Without it, the policy can drift into strange answers that the reward model happens to love. We'll see exactly that in a minute.
InstructGPT and ChatGPT
Does it work? In the InstructGPT paper, Ouyang and colleagues, twenty twenty two, labellers preferred the answers of a one point three billion parameter model trained this way. Over those of the hundred and seventy five billion parameter GPT-3. More than a hundred times smaller, and preferred. ChatGPT used the same recipe for dialogue. Many of the details, like the data and the model size, were never published. The same Bradley-Terry loss, the same policy gradients from module ten. Just at a much larger scale.
Our toy
We built a tiny version. Forty possible answers. A pretrained policy that mostly gives thirty ordinary answers, and only rarely gives ten strange ones. The strange ones sound extremely confident, and they're wrong. Our labeller only cares about quality. The reward model can't see quality directly. It sees how confident an answer sounds, plus a noisy hint of quality. On ordinary answers, confidence and quality go together. Three thousand comparisons later, it agrees with the labeller on eighty one percent of pairs. Not bad at all. So the reward model learned, sensibly: confident sounds good. On the answers it has seen, that's mostly true.
Pulling the leash
Now the RL step, with the KL price. With a large beta, the policy barely moves. As beta shrinks, it moves further. At first, everything is great. The learned reward goes up, and the true quality goes up with it, from minus point one eight to plus point two two. Push further. The learned reward keeps climbing, to one point eight seven. The true quality falls, to minus one. What happened? The policy found the confident, wrong answers, and now gives them every single time. The reward model loved them. Nobody had checked it there. On our toy, the best true quality came at a KL of about point eight. After that, every extra bit of optimisation made things worse.
Recap
So: RLHF learns a reward from human comparisons, and optimises against it, on a leash. It taught a robot to backflip, and a small model to beat a huge one in people's eyes. And pull the leash too hard, and it optimises the wrong thing. Next time, the last episode of the season: the limits of learning from humans.
Goodhart
The last episode of the season. Let's talk about what can go wrong. You saw it last time. Optimise a learned reward too hard, and the policy finds where the reward model is wrong. There's a popular version of Goodhart's law: when a measure becomes a target, it ceases to be a good measure. RLHF is a machine for turning measures into targets. For chatbots, the danger has a specific shape. A model rewarded for sounding authoritative and helpful can learn to sound that way regardless of the truth. And then it makes things up, confidently. We saw a cousin of this in module eleven, with the boxers. Reward the wrong thing, and agents get creative.
Unreliable preferences
Second problem: human preferences are unreliable. People get tired. People are rushed. People like longer answers, and nicer formatting. Dubois and colleagues, twenty twenty three, saw it clearly. After RLHF-style training, answers became much more detailed, with nicer, list-like formatting. Is a longer answer a better answer? Sometimes. Not always. And a model of human preferences is even less reliable than the humans themselves. Be honest: have you ever upvoted an answer because it looked thorough, without checking it? Long and wrong still looks impressive, at first glance.
Where labels come from
Third: where do the labels come from? Who are the labellers? How are they paid? What do they believe? The CS234 slides point out that labels often come from low-wage workers overseas. The quality and the fairness of that work both matter. And whose opinions end up in the model depends on who labelled the data. Santurkar and colleagues, twenty twenty three, asked exactly that: whose opinions do language models reflect? None of this is a reason to stop. It's a reason to report who labelled your data, and how, as carefully as you report your learning rate.
Condorcet's paradox
Now combine many people. Remember the cycle from two episodes ago? Here it comes back, without anyone being irrational. Three friends, three restaurants. The first ranks them A, B, C. The second goes B, C, A. And the third, C, A, B. Take a majority vote on each pair. A beats B. B beats C. C beats A. Three perfectly consistent people, and the group has a cycle. That's Condorcet's paradox. So learning from human preferences sits right where social choice, economics and AI meet. One reward model for everyone is a strong assumption. And when people genuinely disagree, a single reward model has to pick a side, or average them into something nobody actually wants.
Best-of-n
Fourth: is the full machinery even needed? Dubois and colleagues also found that simple baselines work well. One of them is best-of-n. Sample n answers from the model, and keep the one the reward model likes best. No reinforcement learning at all. On our toy from last time, best of eight was the sweet spot: true quality plus point six two. Best of a hundred and twenty eight: minus point nine. Same lesson, different tool. Search hard enough against a flawed reward, and you'll find its flaws. Best of n has a natural knob: n. Like beta, turn it up slowly, and keep checking with
DPO
real people. And there's a newer idea: direct preference optimisation, Rafailov and colleagues, twenty twenty three. Skip the separate reward model. Optimise the policy on the comparisons directly. It still learns from human preferences, so the questions about labels and labellers don't go away. Under the hood, DPO uses the same Bradley-Terry model and the same KL leash. It just solves for the policy more directly. Fewer moving parts. The same old question: whose preferences, and how carefully were they collected?
Three checks
Before we go, three quick checks, in the spirit of the CS234 quizzes. Does behaviour cloning need the dynamics model? No. It only maps states to actions. Does DAgger need more help from the expert after the demonstrations? Yes. Every round, the expert labels the states the learner visited. And in maximum entropy inverse RL, which steps need the dynamics? Computing the policy, and computing the visit frequencies. Three out of three? You were paying attention. If not, the episodes are still there. That's the nice thing about video.
The season
And that's the season. We started with a robot chasing one number: the reward hypothesis. Any goal, one scalar. Bandits and exploration. Markov decision processes, and dynamic programming. Learning from experience: Monte Carlo, and temporal differences. Then control. Function approximation, and deep networks. Planning, with models and search. Policy gradients, and actors with critics. Learning about many things at once. Twelve modules. Exactly one theorem, from Bellman. And a lot of engineering. And in this module, the humans write the number. Or rather, they whisper it, one comparison at a
Goodbye
time. So: learned rewards get hacked, human labels are noisy and come from real people, and groups of people don't always agree. None of that makes learning from humans a bad idea. It makes it a hard one. Which, in this course, usually means an interesting one. If you keep one slide from this whole course, keep the reward hypothesis. And the word I kept stressing: hypothesis. Thank you for learning with me this season. Now go write a good paper. And put me on it.
5:18Episode 47Learning from demonstrationsShowing can be easier than explaining.
5:14Episode 48Maximum-entropy inverse RLMatch the expert, and commit to nothing else.
5:08Episode 49From preferences to rewardsComparisons are cheap; Bradley–Terry turns them into scores.
5:30Episode 50RLHF: from backflips to chatbotsLearn a reward from people, then optimise it on a leash.
5:26Episode 51The limits of RLHFLearning from humans is hard, which makes it interesting.
Interactive lab
Bradley–Terry lab
Compare answers two at a time, the way people label data for RLHF, and watch a Bradley–Terry model turn your choices into a score for each answer. Add simulated comparisons and see how many it needs.
The Bradley–Terry model says P(i beats j) = σ(rᵢ − rⱼ). Fitting the scores r to comparisons is the reward-model step of RLHF. The six answers are made up for this lab.
From “this one is better” to a score
People find it easier to compare two answers than to grade one. A Bradley–Terry model turns many comparisons into one score per answer.
A tie counts as half a win for each side. The small penalty keeps scores finite when one answer wins every time.
A policy is then trained to produce answers the reward model scores highly, usually with a KL term that keeps it close to where it started.
Which answer is more helpful?
“My robot keeps bumping into the same wall. Why?”
Fitted scores
One bar per answer, centred at 0.
Agreement: the share of comparisons (ties left out) in which the fitted model gives the chosen answer more than a 50% chance.
P(row beats column)
What the fitted model predicts for every pair.
Play
A game that goes with this lecture, and what to look for while you play.
Echo Heist
Teach a little robot. Steal back a city.
In this lecture: Echo Heist’s learners include an imitation one: a policy learned from examples rather than from reward. Compare it with the learners that train on reward.
Choose what your partner Echo senses, which actions it can take and what success means, then let a real learner train in your browser: tabular, planning, policy-gradient, deep-RL or imitation. When the door opens, the policy is frozen and Echo runs with what it learned.

