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

Free lesson

Direct preference optimisation by hand

After this lesson: I can work out the DPO loss for a preference pair by hand.

60 min lesson2 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

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

WordWhat it meansExample
DPOdirect preference optimisation: training on pairs with no reward model
Policythe model being trained
Reference modela frozen copy of the model before DPO
Log-probabilitythe log of the chance a model gives an answer-1.2
Betahow strongly the policy is held near the reference0.5

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

The 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 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

The 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

StepWorkingResult
Chosen-1.0 minus -1.20.2
Rejected-2.0 minus -1.7-0.3
Margin0.5 times (0.2 minus -0.3)0.25
Sigmoidsigmoid of 0.250.562
Lossminus log of 0.5620.576

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: the DPO loss of one pair

Code: python
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

Command
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

Command
docker exec jupyter python3 steps/dpo.py

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

What dpo.py printed at step 150

BetaLossABCD
Reference0.6930.40.30.20.1
0.50.0540.010.990.00.0
2.00.0030.080.90.010.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 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: 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.

Code: python
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

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.