Three models, or just two?
RLHF needs the model, a reward model, a copy of the starting model and a reinforcement learning loop. That is a lot to build and to keep steady.
In 2023 researchers showed that the same votes can train the model directly, with one loss you can work out on paper. You will do exactly that.
By the end of this lesson
Note
I can work out the DPO loss for a preference pair by hand.
Key words
| Word | What it means | Example |
|---|---|---|
| DPO | direct preference optimisation: training on pairs with no reward model | |
| Policy | the model being trained | |
| Reference model | a frozen copy of the model before DPO | |
| Log-probability | the log of the chance a model gives an answer | -1.2 |
| Beta | how strongly the policy is held near the reference | 0.5 |
The cells students fill in are left blank in this preview.
Starter
Have a go
Starter
4 questionsThe model is its own reward model
DPO keeps two models: the policy, which is trained, and a frozen reference model. For any answer, beta times the policy's log-probability minus the reference's works as a reward. It is called the implicit reward.
So the Bradley-Terry loss from lesson 3 can be written with these rewards. No separate reward model and no sampling loop are needed.
RLHF and DPO side by side
flowchart TB
V["Votes on pairs"] --> R["Fit a reward model"]
R --> L["RL loop: write, score, update"]
L --> M1["Tuned model"]
V --> D["DPO loss on each pair"]
D --> M2["Tuned model"]Check
Have a go
Check
3 questionsThe DPO loss in four steps
Take one pair. First, for the chosen answer, subtract the reference log-probability from the policy one. Second, do the same for the rejected answer.
Third, take the chosen result minus the rejected one and multiply by beta: the margin. Fourth, the loss is minus the log of the sigmoid of the margin. A bigger margin gives a smaller loss.
Worked example: one pair at beta 0.5
| Step | Working | Result |
|---|---|---|
| Chosen | -1.0 minus -1.2 | 0.2 |
| Rejected | -2.0 minus -1.7 | -0.3 |
| Margin | 0.5 times (0.2 minus -0.3) | 0.25 |
| Sigmoid | sigmoid of 0.25 | 0.562 |
| Loss | minus log of 0.562 | 0.576 |
The cells students fill in are left blank in this preview.
Check
Have a go
Check
3 questionsTry it: the DPO loss of one pair
import math
def sigmoid(x):
return 1 / (1 + math.exp(-x))
beta = 0.5
# Log-probabilities of the whole answer, from the model being tuned and the reference.
policy_chosen, ref_chosen = -1.0, -1.2
policy_rejected, ref_rejected = -2.0, -1.7
chosen_ratio = policy_chosen - ref_chosen # 0.2: chosen got more likely
rejected_ratio = policy_rejected - ref_rejected # -0.3: rejected got less likely
margin = beta * (chosen_ratio - rejected_ratio)
loss = -math.log(sigmoid(margin))
print("margin", round(margin, 3), "loss", round(loss, 3))
# Set policy_chosen to -1.2 and policy_rejected to -1.7. What is the loss now?
Make a free account to save your work and track your progress.
Beta holds the policy near the reference
In the lab, one prompt has four answers, A to D, with reference chances 0.4, 0.3, 0.2 and 0.1. People preferred B to A, B to C and A to D.
With beta 0.5, after 150 steps B rose to 0.99 and A fell to 0.01. With beta 2.0, the loss fell faster, yet B stopped at 0.9 and A at 0.08. A larger beta keeps the policy closer to the reference.
Write the DPO script into the lab
docker exec jupyter sh -c "printf '%s\n' 'import numpy as np' 'ref = np.log(np.array([0.4, 0.3, 0.2, 0.1]))' 'pairs = [[1, 0], [1, 2], [0, 3]]' 'def logp(z):' ' return z - np.log(np.exp(z).sum())' 'def run(beta, steps):' ' z = ref.copy()' ' for step in range(steps + 1):' ' lp, lr = logp(z), logp(ref)' ' m = beta * np.array([(lp[w] - lr[w]) - (lp[l] - lr[l]) for w, l in pairs])' ' s = 1 / (1 + np.exp(-m))' ' if step % 50 == 0:' ' print(\"beta\", beta, \"step\", step, \"loss\", round(float(-np.log(s).mean()), 3), \"chances\", np.exp(lp).round(2).tolist())' ' g = np.zeros(4)' ' for (w, l), sk in zip(pairs, s):' ' g -= beta * (1 - sk) * (np.eye(4)[w] - np.eye(4)[l])' ' z -= 1.0 * g / len(pairs)' 'run(0.5, 150)' 'run(2.0, 150)' > steps/dpo.py"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Train with DPO at two betas
docker exec jupyter python3 steps/dpo.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
What dpo.py printed at step 150
| Beta | Loss | A | B | C | D |
|---|---|---|---|---|---|
| Reference | 0.693 | 0.4 | 0.3 | 0.2 | 0.1 |
| 0.5 | 0.054 | 0.01 | 0.99 | 0.0 | 0.0 |
| 2.0 | 0.003 | 0.08 | 0.9 | 0.01 | 0.0 |
The cells students fill in are left blank in this preview.
A common mistake
Warning
Many people think DPO makes every chosen answer more likely. It widens the gap between chosen and rejected. A was chosen over D, yet its chance fell from 0.4, because A also lost to B. Check the chances, not only the loss.
Check
Have a go
Check
3 questionsAssignment: the DPO loss
Work out the DPO loss in code, as you did by hand.
implicit_reward(logp, ref_logp, beta) is beta times the difference. dpo_loss(pair, beta) takes [policy_chosen, ref_chosen, policy_rejected, ref_rejected] and returns minus the log of the sigmoid of the margin. mean_dpo_loss(pairs, beta) is the mean over a list of pairs.
import math
def implicit_reward(logp, ref_logp, beta):
# beta times (the policy log-probability minus the reference one).
return 0
def dpo_loss(pair, beta):
# pair is [policy_chosen, ref_chosen, policy_rejected, ref_rejected].
# -log(sigmoid(implicit reward of chosen - implicit reward of rejected)).
return 0
def mean_dpo_loss(pairs, beta):
# The mean of dpo_loss over the pairs.
return 0
Make a free account to save your work and track your progress.
Exit quiz
Have a go