Reward Learning

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.

Fool the goal classifier

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

Where Rewards Come From

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.

Weigh a walking reward

Each bar is the reward of one behaviour under your weights. The agent picks the tallest bar. Try to make Walk win.

2.0
1.0
0.5

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 rewardExampleWeak point
Built inGame score, Go win or lossMost real tasks have none
Written by hand2 × speed + 1 × uprightThe agent finds the gaps
Learned from examples of successPhotos of a folded towelFooled by states it never saw
Learned from demonstrationsInverse RL, GAILNeeds a person who can do the task
Learned from preferences"Clip A is better than clip B"Many labels; the policy drifts past them

The road

  1. Ways to say what you want: what each signal tells the agent, and its cost.
  2. A goal classifier as the reward: the shading in the hero.
  3. How the agent fools the classifier: the run that ends at the table's edge.
  4. Feed the agent's states back: the hero's switch, plus inverse RL and GAIL.
  5. Learn from comparisons: the Bradley-Terry model.
  6. Train the reward model in a loop: the preference loss and fresh labels.
  7. RLHF for language models: three stages and a KL leash.
  8. AI feedback and Constitutional AI: a model as the judge.
  9. Rewards the agent makes itself: curiosity and self-play.
  10. The field guide: terms, numbers, code and links.
A walking robot's reward goes up every day, but it walks worse. What is the most likely cause?

Chapter 1

Ways to Say What You Want

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.

See what each signal says

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.

SignalThe person givesStrengthWeak point
Written rewardA formula r(s, a)No data neededGaps the agent finds
DemonstrationsWhole pathsShows how, step by stepCostly; a copy cannot beat the person
Goal photosStates of success and failureCheap to collectSays where to end, not how
Preferences"A is better than B"Works when success has no photoMany labels, some noisy
Language"Put the red cup on the shelf"Natural to giveAmbiguous
AI feedbackPrinciples for a model judgeCheap at scaleThe 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.

You want a reward for "a polite, helpful reply." No photo shows success. Which signal fits best?

Chapter 2

A Goal Classifier as the Reward

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.

Say it aloud

r of s equals sigma of f-phi of s.

r(s)
r of s the reward for state s, from 0 to 1.
σ
sigma the sigmoid, 1 divided by 1 plus e to the minus z. It maps any number into 0 to 1.
fφ(s)
f-phi of s the logit: the network's raw score for s, with weights phi.
In plain words

Show the state s to the network. Squash its logit with sigma. The result is the reward r of s.

With numbers

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.

Say it aloud

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.

L(φ)
L of phi the loss: the number that training makes small.
1/N
one over N divide by the number of photos, to get an average.
Σi
the sum over i one term for each photo.
yi
y-i the label of photo i: 1 for success, 0 for failure.
log σ(·)
log sigma of f-phi of s-i the log of the chance of success the classifier gives photo i.
log(1 − σ(·))
log of one minus sigma the log of the chance of failure it gives photo i.
In plain words

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 numbers

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.

Score one state, then grade the score

The warm curve is the reward sigma. The other curve is the loss for the label you pick. Drag the logit.

2.1

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.

A success photo gets a logit of 0. What does it add to the loss?

Chapter 3

How the Agent Fools the Classifier

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.

Say it aloud

The expected value of the max of c-1 through c-n equals n over n plus 1.

E[·]
the expected value the average over many repeats.
max
the max the largest value in the list.
ci
c-i the classifier's confidence on the i-th OOD state, uniform from 0 to 1.
n
n the number of OOD states the agent visits.
In plain words

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 numbers

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.

  1. All n confidences fall below x with chance x to the n.
    P(max ≤ x) = xn
  2. The slope of that curve is the density of the max.
    p(x) = n xn−1
  3. Average x under that density, from 0 to 1.
    ∫01 x · n xn−1 dx = n / (n + 1)

Visit more states, find a better fake

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.

20

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.

Under the uniform model, the agent visits 19 OOD states. What is the average best fake confidence?

Chapter 4

Feed the Agent's States Back

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.

  1. Train the classifier on success photos and failure photos.
  2. Run RL with the classifier's probability as the reward. Keep the states the agent visits.
  3. Add those states to the failure photos.
  4. Retrain with balanced batches: half success, half failure in every batch.
  5. Go back to step 2.

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.

Say it aloud

C-star of s equals p-plus of s, divided by p-plus of s plus p-minus of s.

C*(s)
C-star of s the best classifier's chance of success at state s.
p+(s)
p-plus of s how densely the success photos cover s.
p−(s)
p-minus of s how densely the negatives cover s, the agent's visits included.
In plain words

At each state, compare how often success photos and negatives land there. C-star is the success share.

With numbers

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.

Move the agent, watch the classifier follow

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.

0.90

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.

MethodReal sideFake sideAgent's reward
Adversarial goal classifierSuccess statesThe agent's statesThe classifier's probability
GAILExpert state-action pairsThe agent's state-action pairsThe discriminator's score
GANReal imagesGenerated imagesThe generator's loss, negated
The agent now reaches the goal, and its states fill the negatives there as densely as the success photos. With balanced batches, what does the classifier say at the goal?

Chapter 5

Learn From Comparisons

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.

Say it aloud

The probability that tau-w beats tau-l equals sigma of R of tau-w minus R of tau-l.

P(·)
the probability that how often a person makes this choice.
τw
tau-w the trajectory the person picked, the winner.
≻
beats the person prefers the left one to the right one.
τl
tau-l the trajectory the person rejected, the loser.
σ
sigma the sigmoid, which maps any gap into a chance from 0 to 1.
R(τ)
R of tau the sum of the reward model's rewards over every step of tau.
In plain words

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 numbers

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.

Turn a reward gap into a choice

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.

1.1

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.

Two trajectories have the same total learned reward. What chance does Bradley-Terry give that a person picks the first one?

Chapter 6

Train the Reward Model in a Loop

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.

Say it aloud

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.

L(φ)
L of phi the preference loss, which training makes small.
Σ(w,l)∈D
the sum over pairs w, l in D one term for each labelled pair: winner w, loser l.
log σ(·)
log sigma of the gap the log of the chance the model gives the person's real choice.
Rφ(τ)
R-phi of tau the total reward the model with weights phi gives trajectory tau.
In plain words

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 numbers

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:

  1. Run the policy and record short clips.
  2. Show pairs of clips to a person. Record the winner.
  3. Update phi on all the pairs so far.
  4. Train the policy with RL on the learned reward.
  5. Repeat. The new clips come from the new policy.

Learn a taste from comparisons

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.

A labeler ranks 5 responses to one prompt. How many pairs does that give the reward model?

Chapter 7

RLHF for Language Models

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.

  1. Pretraining: predict the next token on web text. The model writes fluently but has no goal.
  2. Supervised fine-tuning (SFT): train on answers that people wrote. The model learns the form of a helpful reply.
  3. RL: people compare pairs of answers. A reward model learns from the pairs with the Chapter 6 loss. RL tunes the model to score high.

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.

Say it aloud

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.

maxθ
maximize over theta tune the model's weights theta to make the rest large.
Ex, y~πθ
the expected value, y drawn from pi-theta the average over prompts x and the answers y the tuned model writes.
rφ(x, y)
r-phi of x, y the reward model's score for answer y to prompt x.
β
beta the strength of the leash.
KL(πθ ‖ πSFT)
the KL from pi-theta to pi-SFT how far the tuned model moved from the SFT model, in nats.
In plain words

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 numbers

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.

Set the leash

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.

0.10

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.

Why does RLHF subtract beta times the KL to the SFT model?

Chapter 8

AI Feedback and Constitutional AI

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.

  1. Supervised phase: the model answers, critiques its answer against a principle, and rewrites it. Fine-tune the model on the rewrites.
  2. RL phase: the model writes two answers. A feedback model picks the better one under a principle. Train a preference model on these AI labels, then run RL against it.

Give the judge a taste for length

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.

0.60

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.

An AI judge prefers the longer answer in 80% of pairs, but people do not care about length. What happens to a model trained with RLAIF on this judge?

Chapter 9

Rewards the Agent Makes Itself

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.

Say it aloud

r-int of s-t and a-t equals the squared length of f of s-t, a-t minus s-t-plus-one.

rint
r-int the intrinsic reward: a reward the agent makes for itself.
f(st, at)
f of s-t, a-t the forward model's guess of the next state.
st+1
s-t-plus-one the next state that came about.
‖ · ‖
the length of how big the miss is, over all coordinates.
2
squared so the result is the sum of each coordinate's miss, squared.
In plain words

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 numbers

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.

Watch curiosity meet a noisy TV

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.

Why does a curious agent stare at a TV of random static?

Chapter 10

The Field Guide

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.

Which signal to use

IfUseWatch for
You can write the number (distance, score)A written rewardVideos that disagree with the curve
You can photograph successA goal classifier, with adversarial updatesHigh scores away from the goal
You can do the task yourselfDemonstrations: imitation, inverse RL, GAILStates the expert never visited
People can compare outcomesPreferences and a reward modelReward up, human ratings down
Human labels cost too muchRLAIF with a written constitutionThe judge's biases, such as length
There is no signal yetCuriosity or self-play to learn skillsNoisy TVs

The equations

NameEquationSay it
Classifier rewardr(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 nn / (n + 1)n over n plus 1
Best classifierp+ / (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 objectiveE[rφ] − β KL(πθ ‖ πSFT)reward minus beta times the drift
Curiosity‖f(s, a) − s′‖2the squared miss of the forward model

The numbers from this page

WhatNumberWhy it matters
Walking reward, weights 2, 1, 0.5fall 10, walk 4.4A written reward pays for the wrong thing
Sigma of 2.1 and of 4.70.89 and 0.99A fake can outscore the goal
Best fake of 99 OOD states0.99 on averageMore search, better exploits
Classifier at equilibrium0.5The game stops when agent and goal look alike
Unbalanced batches, 10 to 10.09 where densities matchBalance or the reward starves
Bradley-Terry, gap 1.10.75; loss 0.287Pairs the model gets right push little
Ranking K responsesK(K−1)/2 pairs: 6 at 4, 36 at 9Rankings give many labels per prompt
Toy RLHF at beta 0.1KL 12, proxy 7.60, objective 6.40The leash sets how far the model drifts

Before you trust a learned reward

The core code

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

Keep going

The takeaway. A learned reward is right only where it has data. RL goes where it has none. Every method here keeps feeding the reward data from where the policy goes, or keeps the policy near the data.
Which practice protects against reward overoptimization in every method on this page?

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.

Credit and source

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.

CS 224R: Reward Learning
The course site · Deep RL from Human Preferences · InstructGPT · Back to Gleams