Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

Reward models and RLHF

After this lesson: I can fit a reward model to votes between pairs of answers.

70 min lesson3 commandsJupyterLab data science lab: pandas, Matplotlib and scikit-learn in the browser

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

Which of these two answers is better?

Ask a person to score an answer about resetting a password out of 10, and two people give a 6 and a 9. Show them two answers side by side and ask which is better, and they mostly agree.

That second question is how human taste gets into a model. You will turn such votes into a reward model and see how it can be fooled.

By the end of this lesson

Note

I can fit a reward model to votes between pairs of answers.

Key words

WordWhat it means
Preference pairtwo answers to one prompt and which one a person chose
Reward modela model that gives an answer a score
Sigmoida function that turns any number into a chance from 0 to 1
Bradley-Terry modelthe chance A beats B is the sigmoid of their reward difference
RLHFreinforcement learning from human feedback
Reward hackingraising the score without getting better

The cells students fill in are left blank in this preview.

Starter

Have a go

Starter

4 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

A vote depends on a reward difference

A reward model gives each answer a number. The Bradley-Terry model links those numbers to votes. The chance that A beats B is the sigmoid of reward A minus reward B.

Equal rewards give 0.5, a coin toss. A lead of 2 gives about 0.88. Only the difference matters, so adding 10 to every reward changes nothing.

Worked example: reward difference and chance

Reward A minus reward B-10123
Chance A wins0.270.50.730.880.95

The cells students fill in are left blank in this preview.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Try it: chances and a vote's loss

Code: python
import math

def sigmoid(x):
    return 1 / (1 + math.exp(-x))

# The chance that A beats B depends only on the difference of rewards.
for diff in [-1, 0, 1, 2, 3]:
    print("reward A minus B", diff, "chance A wins", round(sigmoid(diff), 2))

# The loss for one vote where A won: small when A is well ahead.
reward_a = 3.5
reward_b = 2.9
print("loss", round(-math.log(sigmoid(reward_a - reward_b)), 3))
# Swap the two rewards. What happens to the loss?

Make a free account to save your work and track your progress.

Fitting the reward model to votes

For each vote, the loss is minus the log of the chance the model gave the winner. Fitting nudges the weights to make the winners more likely, the same gradient descent as before.

A real reward model is a language model with one score on top, reading the whole answer. Ours reads three features: is it correct, is it polite, and its length in hundreds of words.

Write the reward model script into the lab

Command
docker exec jupyter sh -c "printf '%s\n' 'import numpy as np' 'answers = {\"A\": [1, 1, 1.2], \"B\": [1, 0, 1.0], \"C\": [0, 1, 0.4],' '           \"D\": [0, 0, 0.3], \"E\": [1, 1, 0.5], \"F\": [0, 1, 0.9]}' 'votes = [[\"A\", \"B\", 8, 2], [\"A\", \"C\", 9, 1], [\"A\", \"D\", 10, 0], [\"A\", \"E\", 7, 3], [\"A\", \"F\", 9, 1],' '         [\"B\", \"C\", 8, 2], [\"B\", \"D\", 9, 1], [\"B\", \"E\", 4, 6], [\"B\", \"F\", 8, 2], [\"C\", \"D\", 8, 2],' '         [\"C\", \"E\", 1, 9], [\"C\", \"F\", 4, 6], [\"D\", \"E\", 0, 10], [\"D\", \"F\", 2, 8], [\"E\", \"F\", 8, 2]]' 'X, n = [], []' 'for a, b, wa, wb in votes:' '    d = np.array(answers[a]) - np.array(answers[b])' '    X += [d, -d]' '    n += [wa, wb]' > steps/reward.py"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Finish writing the script

Command
docker exec jupyter sh -c "printf '%s\n' 'X, n = np.array(X), np.array(n)' 'w = np.zeros(3)' 'for step in range(101):' '    p = 1 / (1 + np.exp(-X @ w))' '    if step in [0, 5, 20, 100]:' '        print(\"step\", step, \"loss\", round(float((-n * np.log(p)).sum() / n.sum()), 3), \"weights\", w.round(2).tolist())' '    w += 2.0 * X.T @ (n * (1 - p)) / n.sum()' 'for name in answers:' '    print(name, answers[name], \"reward\", round(float(np.array(answers[name]) @ w), 2))' 'p = 1 / (1 + np.exp(-(np.array(answers[\"E\"]) - np.array(answers[\"B\"])) @ w))' 'print(\"chance E beats B\", round(float(p), 2))' 'for new in [[1, 0, 0.5], [0, 1, 3.0]]:' '    print(\"new\", new, \"reward\", round(float(np.array(new) @ w), 2))' >> steps/reward.py"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Fit the reward model to 150 votes

Command
docker exec jupyter python3 steps/reward.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

What reward.py learnt

AnswerCorrectPoliteHundreds of wordsReward
A111.24.2
E110.53.52
B101.02.95
F010.91.92
C010.41.44
D000.30.29

The cells students fill in are left blank in this preview.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

RLHF optimises against the reward model

In RLHF, the tuned model writes answers, the reward model scores them, and reinforcement learning changes the model to earn higher scores.

A penalty is taken off for drifting far from the starting model, often measured as KL divergence. Without it, the model finds answers the reward model overrates.

The RLHF loop

flowchart LR
  A["Tuned model"] --> B["Writes answers"]
  B --> C["Reward model scores them"]
  C --> D["Score minus drift penalty"]
  D --> E["Update the model"]
  E --> B

A common mistake

Warning

Many people think a high reward means a good answer. A reward model is learnt from a limited set of votes. In the lab, a wrong 300-word answer scored 3.94, above a correct short one at 2.47, because long answers usually won. Push too hard on the score and you get reward hacking.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Assignment: fit a reward model

Fit a Bradley-Terry reward model to preference pairs, as in the lesson.

sigmoid(x) is 1 over 1 plus e to the minus x. reward(weights, features) is the sum of each weight times its feature. pair_loss(weights, pairs) is the mean loss over [chosen, rejected] pairs. fit_step(weights, pairs, rate) returns new weights after one step, as the starter describes.

Code: python
import math


def sigmoid(x):
    return 0.5


def reward(weights, features):
    # The sum of each weight times its feature.
    return 0


def pair_loss(weights, pairs):
    # pairs is a list of [chosen, rejected], each a list of features.
    # The mean of -log(sigmoid(reward of chosen - reward of rejected)).
    return 0


def fit_step(weights, pairs, rate):
    # Return NEW weights. For each pair, s = 1 - sigmoid(difference of rewards).
    # Weight j goes up by rate times the mean over pairs of s * (chosen[j] - rejected[j]).
    return weights

Make a free account to save your work and track your progress.

Exit quiz

Have a go

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.