Most tasks have no score, so we learn one from photos of success, demonstrations or comparisons. An agent that maximizes a fixed goal classifier finds a state the classifier never saw and scores 0.98 with no success at all.
Learn where rewards come from, how agents fool a learned reward, and the fixes: adversarial updates, preferences, a KL leash and AI judges.
Press Run the agent. It pushes the block to the edge of the table, where no training photo looked. Then switch on Add its states as negatives and run it two or three more times. Then we build it piece by piece: goal classifiers, the exploit, the adversarial fix, preferences, RLHF and AI feedback.
You need a little Python and what a probability is. We build the rest from zero.
Re-taught from the reward learning lecture of Stanford CS 224R: Deep Reinforcement Learning. The explanations, toys and numbers here are our own; every toy number is illustrative.
Illustrative toy. The state is the block's position on a table. The classifier is logistic regression on 28 features: a bias, the two coordinates and 25 bumps. It trains with balanced batches on 16 success photos and 40 failure photos, all from the left 60% of the table. Each run, the agent climbs the score from 12 random starts and keeps the best end.
Chapter 0
See why most tasks give the agent no score, and what goes wrong when you write one by hand
In Breakout, the score goes up when a brick breaks. The game hands the agent its reward. A robot that folds a towel gets no such number. When is the towel folded well enough? Somebody must write the reward, or the robot must learn it.
The reward is the number the agent gets after each step. The agent tries to make the total large. The reward specification problem is the gap between the number you write and the task you mean. The agent maximizes the number, not your meaning.
Each bar is the reward of one behaviour under your weights. The agent picks the tallest bar. Try to make Walk win.
Illustrative numbers. Fall forward: speed 5, upright 0, feet on the ground 0. Stand still: 0, 1, 2. Walk: 1.5, 0.9, 1.
With weights 2, 1 and 0.5, falling forward scores 2 × 5 = 10. Standing scores 1 + 0.5 × 2 = 2. Walking scores 3 + 0.9 + 0.5 = 4.4. The robot falls on its face, because 10 is more than 4.4.
The failure. Weights 1, 4 and 1 make Walk win, 6.1 against 6 for standing. Move one weight a little and Walk loses again. The symptom is a reward that climbs while the behaviour gets worse. To measure it, watch videos of the policy, not only the reward curve. The fix is this lesson: learn the reward from what people can show or judge.
| Source of reward | Example | Weak point |
|---|---|---|
| Built in | Game score, Go win or loss | Most real tasks have none |
| Written by hand | 2 × speed + 1 × upright | The agent finds the gaps |
| Learned from examples of success | Photos of a folded towel | Fooled by states it never saw |
| Learned from demonstrations | Inverse RL, GAIL | Needs a person who can do the task |
| Learned from preferences | "Clip A is better than clip B" | Many labels; the policy drifts past them |
Chapter 1
Compare the signals a person can give, by what each tells the agent and what it costs
A person can tell an agent the task in several ways. A task specification is any signal a person gives to say what they want. Signals differ in two things: how much they say, and how much human time they cost.
Pick a signal. The map shows what the agent learns from it. The bar shows the human time it costs, on a log scale.
Illustrative pick-and-place costs: 2 weeks of tuning a written reward; 50 demonstrations at 3 minutes; 20 success and 20 failure photos in 10 minutes; 500 comparisons at 10 seconds each.
With these costs, demonstrations take 50 × 3 = 150 minutes. Comparisons take 500 × 10 s = 5,000 s, about 83 minutes. Goal photos take 10 minutes, but they say only where to end.
| Signal | The person gives | Strength | Weak point |
|---|---|---|---|
| Written reward | A formula r(s, a) | No data needed | Gaps the agent finds |
| Demonstrations | Whole paths | Shows how, step by step | Costly; a copy cannot beat the person |
| Goal photos | States of success and failure | Cheap to collect | Says where to end, not how |
| Preferences | "A is better than B" | Works when success has no photo | Many labels, some noisy |
| Language | "Put the red cup on the shelf" | Natural to give | Ambiguous |
| AI feedback | Principles for a model judge | Cheap at scale | The judge's biases |
Comparing is easier than scoring. Ask two people to rate a clip from 1 to 10, and one says 6 while the other says 8. Ask them which of two clips is better, and they agree more often. Preference learning and RLHF stand on this fact.
The failure. Goal photos say where to end, not how to get there. If success is rare, a learner that gets reward only at success may never reach it by chance. The symptom is a flat learning curve. Measure the share of episodes that ever get a high score. The fix is a reward that rises toward the goal, which the classifier's probability gives you (next chapter), or a few demonstrations to start from.
Chapter 2
Train a classifier on photos of success and failure, and use its probability as the reward
A robot must push a block onto a target. You take 50 photos with the block on the target and 200 with it anywhere else. A goal classifier is a network that looks at one state and says how likely it is a success.
Call the state s. The network gives one raw number for it, the logit. Its weights are φ (phi), so the logit is f-phi of s. The sigmoid σ squashes any number into the range 0 to 1. That value is the reward.
r of s equals sigma of f-phi of s.
Show the state s to the network. Squash its logit with sigma. The result is the reward r of s.
With made-up logits: near the target, f-phi of s is 2.1, and sigma of 2.1 is 1 / (1 + e−2.1) = 0.89. Far away, a logit of −2.2 gives 0.10. The reward rises as the block nears the target.
Train phi with the binary cross-entropy loss. Call the label of photo i y-i: 1 for success, 0 for failure. Call the number of photos N.
L of phi equals minus one over N, times the sum over i of: y-i times log sigma of f-phi of s-i, plus one minus y-i, times log of one minus sigma of f-phi of s-i.
For each photo, take the log of the chance the classifier gave the right label. Average over all N photos and flip the sign. A confident wrong answer costs the most.
With made-up logits: a success photo with logit 2.1 costs −log 0.891 = 0.116. A failure photo with logit −1.0 gets a success chance of 0.269, so it costs −log 0.731 = 0.313. L is the average, 0.214.
The warm curve is the reward sigma. The other curve is the loss for the label you pick. Drag the logit.
Natural log throughout.
The failure. Use the raw logit as the reward, and the agent hunts for a state with a logit of 1,000. The symptom is a reward with no ceiling; log the largest reward in each batch to see it. The fix is the sigmoid: no state is worth more than 1, a sure success. But the classifier still answers for states it never saw. That is the next chapter.
Chapter 3
Watch strong optimization find the states where the classifier is wrong and sure
The classifier saw 250 photos. The agent tries thousands of states, and many look like no photo in the training set. These are out-of-distribution (OOD) states. On them, the classifier still gives a confident number.
In the hero, the agent pushes the block to the table's edge. No photo showed the edge, so the classifier extends its trend there and says 0.98. This is classifier exploitation: the agent finds a state that scores high and is not a success.
How likely is a high wrong score? Take a pessimistic model. The classifier gives each OOD state a random confidence c, anywhere from 0 to 1 with equal chance. The agent visits n such states and keeps the best one.
The expected value of the max of c-1 through c-n equals n over n plus 1.
Draw n random confidences and keep the largest. Average that largest value over many repeats. It is n over n plus 1, which creeps toward 1 as n grows.
With n = 9, the best fake state averages 0.90. With n = 99, it averages 0.99. A real success with logit 2.1 scores 0.89, so after 99 OOD visits a fake beats the real goal.
Each dot is one OOD state's random confidence. The red dot is the best fake the agent keeps. The green line is a real success at 0.89. Raise n and press Draw.
Illustrative model: confidences are uniform from 0 to 1. A real classifier is not uniform, but strong optimization finds its highest errors in the same way.
The failure. The better the RL, the worse the exploit, because more states visited means a higher best fake. The symptom is a classifier reward that rises while true success stays flat. To measure it, hand-label a sample of the states with the highest reward. The fix is in the next chapter.
Chapter 4
Add the agent's own states to the negatives, retrain, and repeat until only real success scores high
Each time the agent finds a hole, label its states as failures and retrain. The classifier learns that the hole is not success either. The agent looks for a new hole, and the classifier patches that one too. This is an adversarial classifier; VICE (Fu et al., 2018) builds on it.
Where does the game stop? Call the density of success photos at state s p-plus of s. Call the density of negatives there p-minus of s; it includes the agent's own visits. With balanced batches, the best classifier is this.
C-star of s equals p-plus of s, divided by p-plus of s plus p-minus of s.
At each state, compare how often success photos and negatives land there. C-star is the success share.
With made-up densities: at the goal, p-plus is 3 and p-minus is 1, so C-star is 3 / 4 = 0.75. When the agent lives at the goal, its visits raise p-minus to 3, and C-star falls to 0.5. The two sides now look alike, so the game stops.
Why this form: at state s, the loss is p-plus times −log C, plus p-minus times −log(1 − C). It is lowest where p-plus / C = p-minus / (1 − C). Solve for C.
Green is the success photos, blue the starting negatives, purple the agent's own visits. The warm curve is C-star. Slide the agent along the line.
Illustrative 1-D densities. The agent's visits make up 90% of the negatives. With balance off, negatives outnumber success photos 10 to 1.
The failure. Turn balance off. Where p-plus equals p-minus, the classifier now says 1 / 11 = 0.09, not 0.5, and the reward starves. The symptom is a reward near 0 everywhere. Measure the score on held-out success photos. The fix is balanced batches.
The same game works with demonstrations. Inverse RL asks which reward makes the expert's paths look best, then trains a policy on it. GAIL (Ho and Ermon, 2016) skips the explicit reward and uses a discriminator's score.
| Method | Real side | Fake side | Agent's reward |
|---|---|---|---|
| Adversarial goal classifier | Success states | The agent's states | The classifier's probability |
| GAIL | Expert state-action pairs | The agent's state-action pairs | The discriminator's score |
| GAN | Real images | Generated images | The generator's loss, negated |
Chapter 5
Turn "A is better than B" into a probability with the Bradley-Terry model
What is success in a conversation? No photo shows it. But a person can watch two tries and say which is better. A preference is one such label: trajectory A beats trajectory B.
We need a model of how a person picks. A reward model gives each step a learned reward. Add those rewards along a trajectory τ (tau) to get its total, R of tau. Call the winner tau-w and the loser tau-l. The Bradley-Terry model (Bradley and Terry, 1952) says: the bigger the gap in totals, the more often the person picks the winner.
The probability that tau-w beats tau-l equals sigma of R of tau-w minus R of tau-l.
Add the learned rewards along each trajectory. Subtract the loser's total from the winner's. Squash the gap with sigma to get the chance a person picks the winner.
With made-up step rewards 0.1, 0.3, 0.5, 0.7, 0.9 for A and 0.2, 0.2, 0.3, 0.3, 0.4 for B: R of A is 2.5 and R of B is 1.4. Sigma of 1.1 = 1 / (1 + 0.333) = 0.75. The model expects people to pick A 3 times in 4.
Where the sigma comes from: give each trajectory a weight of e to its total, and let the person pick in proportion to the weights. A wins with chance e2.5 / (e2.5 + e1.4) = 12.18 / 16.24 = 0.75. Divide the top and the bottom by e2.5, and the share becomes sigma of the gap.
Left: the two totals. Right: the chance a person picks A. Drag the gap. Then add 1 to every step's reward and watch the chance stay put.
Illustrative totals; B's total starts at 1.4.
The failure. Only the gap matters, so the reward's level is free. The symptom is reward values that drift up or down between training runs. Measure the mean reward on a fixed batch of trajectories. The fix is to normalize the reward model's output, for example to a mean of 0 on that batch, before RL uses it.
Chapter 6
Fit the reward model to comparisons, train the policy on it, and ask again where the policy now goes
Now fit the reward model. Call its weights φ (phi) and the set of labelled pairs D. Choose the weights that make the person's choices most likely.
L of phi equals minus the sum over pairs w, l in D of log sigma of R-phi of tau-w minus R-phi of tau-l.
For each pair, compute the model's chance that the person picks the winner. Take its log, add over all pairs and flip the sign. Making L small raises each winner's total and lowers each loser's.
With the pair from Chapter 5: the gap is 1.1 and sigma is 0.75, so the pair costs −log 0.75 = 0.287. Its gradient pushes each total by 1 − 0.75 = 0.25: up for the winner, down for the loser. A pair the model already gets right at 0.99 pushes only 0.01.
Christiano et al. (2017) run this inside a loop:
Faint bars are the person's hidden taste for six clips. Warm bars are the reward model. Each press shows the person 10 random pairs, and the model trains on every pair so far.
Illustrative: the person picks by Bradley-Terry on the hidden rewards, so some labels go against the taste. The model is one number per clip, trained by gradient descent on the loss above. We draw both sets of bars with their mean at 0.
A ranking gives many pairs at once. A person who ranks K responses gives K(K − 1)/2 pairs: 6 for K = 4 and 36 for K = 9. InstructGPT asked labelers to rank 4 to 9 responses per prompt (Ouyang et al., 2022).
The failure. The policy moves to states with no labels, where the reward model is wrong. This is reward overoptimization, the preference version of Chapter 3. The symptom is a learned reward that rises while people's ratings fall. Measure the model's accuracy on fresh clips from the current policy. The fix is the loop: new labels follow the policy.
Chapter 7
Train a reward model on human comparisons of answers, then tune the model against it on a KL leash
Reward learning became famous by training chat models. RLHF (reinforcement learning from human feedback) has three stages.
In stage 3, the model can drift into text that fools the reward model: Chapter 3 again. So the objective adds a leash to the SFT model. Call the prompt x, the answer y, the tuned model pi-theta and the SFT model pi-SFT. The KL divergence measures how far pi-theta moved from pi-SFT: the average, over its own answers, of the log of the ratio of their two chances.
Maximize over theta: the expected r-phi of x and y, with y drawn from pi-theta, minus beta times the KL from pi-theta to pi-SFT.
Sample answers from the model and score each with the reward model. Subtract beta times how far the model moved from SFT. Tune theta to make that total large.
With the toy curves below: at beta 0.1, the best drift is a KL of about 12 nats. The reward model gives 7.60, the leash costs 0.1 × 12 = 1.2, and the objective is 6.40. True quality there is 5.72, below its peak of 6.40 at a KL of 6.
Warm: the reward model's score. Green: true quality, as people would judge it. The teal dot is where the objective puts the model. Lower beta and watch the two curves part.
Illustrative curves: proxy = 3.8 + 4.4(1 − e−KL/6). Their shape follows Gao, Schulman and Hilton (2022): the proxy keeps rising with KL while true quality peaks and falls.
The failure. At beta 0.02 the model drifts to a KL of 22 nats. The reward model says 8.08, and true quality falls to 4.49. The symptom is odd, repetitive or flattering answers with a high reward. Measure the KL and a small human or held-out score at each step. The fix is a larger beta, or stopping early.
Chapter 8
Replace the human judge with a model that follows written principles, and check its biases
Human labels are slow, and each comparison costs money. RLAIF (RL from AI feedback) asks a language model which of two answers is better. The rest stays the same: a Bradley-Terry reward model, then RL.
Judging is often easier than writing. You can tell which of two proofs is clearer without being able to write either one. So a model can label answers near its own level.
Constitutional AI (Bai et al., 2022) gives the judge a constitution: a short list of written principles, such as "choose the less harmful answer." It has two phases.
Each dot is a pair of answers. Up means A is better; right means A is longer. People pick by quality alone. The judge's line tilts as it likes length more. Red dots are pairs where the judge and people disagree.
Illustrative data: 160 random pairs whose quality gap and length gap are independent. The judge picks A when the quality gap plus bias times the length gap is above 0.
With these pairs, a bias of 0 agrees with people on every pair. A bias of 1 adds the length gap at full weight, and the judge then disagrees on about a quarter of the pairs.
The failure. A judge that likes long answers trains a model that writes long answers, whether people want them or not. The symptom is answer length that rises over training. Measure the judge's agreement with a small set of human labels, and how often it picks the longer answer. The fix is to calibrate against that human set, or to control for length.
Chapter 9
Pay the agent for surprise, or let two agents set each other tasks
Can an agent learn skills with no human signal at all? Two ideas: pay it for surprise, or let it play against itself.
Curiosity pays the agent where its own predictions fail. The agent learns a forward model f that guesses the next state from the state and the action. Call the state s-t, the action a-t and the next state s-t-plus-one.
r-int of s-t and a-t equals the squared length of f of s-t, a-t minus s-t-plus-one.
Guess the next state with f. See what came next. The squared size of the miss is the reward r-int. As f learns a place, the miss shrinks, and the agent moves on.
With made-up states: f guesses (2.0, 1.0) and the real next state is (2.3, 0.6). The miss is (0.3, −0.4), so r-int = 0.09 + 0.16 = 0.25.
Three places: a new room, a known room and a TV of random static. Curves show the prediction miss in each place; bars show where the agent spends its time. Run it, then switch on learned features and run again.
Illustrative: each step, the agent goes where its last miss was largest, with a 10% chance of a random place. In raw pixels the static's miss stays near 0.6; learned features that keep only what actions change ignore it.
The failure. This is the noisy TV problem. Random static never becomes predictable, so curiosity pays for it forever and the agent stares at it. The symptom is an agent parked in front of a random source. Measure the share of time it spends there. A fix is to predict in features that keep only what the agent's actions change (Pathak et al., 2017). It helps, but it does not remove the problem in every case.
Asymmetric self-play (Sukhbaatar et al., 2017) uses two copies of the agent. Alice acts and then stops; Bob must repeat or undo what she did. Alice is paid by how much longer Bob takes than she did; Bob is paid for being fast. Alice must do each task herself, so her tasks stay possible and grow harder as Bob improves. That is a curriculum, a sequence of tasks from easy to hard, with no person in it.
Chapter 10
Keep the choices, the equations, the numbers, a checklist and the core code on one page
Most tasks have no reward, so we learn one: from photos of success, from demonstrations, or from comparisons. Every learned reward has holes where it saw no data, and RL finds them. The fixes keep the reward's data near the policy: feed the agent's states back, keep collecting labels, or leash the policy to a reference model.
| If | Use | Watch for |
|---|---|---|
| You can write the number (distance, score) | A written reward | Videos that disagree with the curve |
| You can photograph success | A goal classifier, with adversarial updates | High scores away from the goal |
| You can do the task yourself | Demonstrations: imitation, inverse RL, GAIL | States the expert never visited |
| People can compare outcomes | Preferences and a reward model | Reward up, human ratings down |
| Human labels cost too much | RLAIF with a written constitution | The judge's biases, such as length |
| There is no signal yet | Curiosity or self-play to learn skills | Noisy TVs |
| Name | Equation | Say it |
|---|---|---|
| Classifier reward | r(s) = σ(fφ(s)) | r of s is sigma of the logit |
| Cross-entropy | −mean[y log σ + (1−y) log(1−σ)] | minus the average log chance of the right label |
| Best fake of n | n / (n + 1) | n over n plus 1 |
| Best classifier | p+ / (p+ + p−) | the success share at each state |
| Bradley-Terry | σ(R(τw) − R(τl)) | sigma of the gap in totals |
| Preference loss | −Σ log σ(gap) | minus the sum of log chances of the real choices |
| RLHF objective | E[rφ] − β KL(πθ ‖ πSFT) | reward minus beta times the drift |
| Curiosity | ‖f(s, a) − s′‖2 | the squared miss of the forward model |
| What | Number | Why it matters |
|---|---|---|
| Walking reward, weights 2, 1, 0.5 | fall 10, walk 4.4 | A written reward pays for the wrong thing |
| Sigma of 2.1 and of 4.7 | 0.89 and 0.99 | A fake can outscore the goal |
| Best fake of 99 OOD states | 0.99 on average | More search, better exploits |
| Classifier at equilibrium | 0.5 | The game stops when agent and goal look alike |
| Unbalanced batches, 10 to 1 | 0.09 where densities match | Balance or the reward starves |
| Bradley-Terry, gap 1.1 | 0.75; loss 0.287 | Pairs the model gets right push little |
| Ranking K responses | K(K−1)/2 pairs: 6 at 4, 36 at 9 | Rankings give many labels per prompt |
| Toy RLHF at beta 0.1 | KL 12, proxy 7.60, objective 6.40 | The leash sets how far the model drifts |
The preference loss and one balanced classifier step, in PyTorch. Both train on fixed data; the RL step around them is any policy optimizer.
pythonimport torch import torch.nn.functional as F def preference_loss(reward_model, tau_w, tau_l): # tau_w, tau_l: [B, T, obs_dim], winner and loser clips R_w = reward_model(tau_w).squeeze(-1).sum(dim=1) # [B], total reward R_l = reward_model(tau_l).squeeze(-1).sum(dim=1) return -F.logsigmoid(R_w - R_l).mean() # Bradley-Terry def classifier_step(clf, opt, success, negatives, batch=64): # balanced: half success photos, half negatives (the agent's states included) h = batch // 2 pos = success[torch.randint(len(success), (h,))] neg = negatives[torch.randint(len(negatives), (h,))] x = torch.cat([pos, neg]) y = torch.cat([torch.ones(h), torch.zeros(h)]) loss = F.binary_cross_entropy_with_logits(clf(x).squeeze(-1), y) opt.zero_grad(); loss.backward(); opt.step() return loss.item() def adversarial_rounds(policy, clf, opt, success, negatives, run_rl, rounds=10, k=200): for _ in range(rounds): reward = lambda s: torch.sigmoid(clf(s)).squeeze(-1).detach() states = run_rl(policy, reward) # [M, obs_dim], states the agent visited negatives = torch.cat([negatives, states]) # feed them back as failures for _ in range(k): classifier_step(clf, opt, success, negatives) return policy, clf
Now press Present or Teach and explain from memory three things: how the agent fools a fixed classifier, why feeding back its states stops the game at 0.5, and how Bradley-Terry turns a comparison into a loss. Then go back to the hero, run it with the switch off and on, and say what changed.
This lesson re-teaches the reward learning lecture of Stanford CS 224R: Deep Reinforcement Learning. The papers behind it: Bradley and Terry (1952); Ho and Ermon, GAIL (2016); Christiano et al., Deep RL from Human Preferences (2017); Pathak et al., curiosity (2017); Sukhbaatar et al., asymmetric self-play (2017); Fu et al., VICE (2018); Singh et al., robot RL without reward engineering (2019); Ouyang et al., InstructGPT (2022); Bai et al., Constitutional AI (2022); Gao, Schulman and Hilton, reward model overoptimization (2022). The toys and numbers here are our own.