519. Train a reward model with the Bradley-Terry loss
RLHF reward models learn from pairs: a human picked response A over response B. The Bradley-Terry model says P(A preferred) = sigmoid(r_A - r_B). Training minimises the negative log of that.
Write reward_loss(r_chosen, r_rejected) for two equal-length arrays of reward scores. Return (loss, accuracy): loss is the mean of -log sigmoid(r_chosen - r_rejected), computed stably, and accuracy is the fraction of pairs where r_chosen > r_rejected.
Inputs can be Python lists or NumPy arrays, so convert them with np.asarray first.
def reward_loss(r_chosen, r_rejected)Example 1
Input: r_chosen = [1.0, 0.5, 2.0], r_rejected = [0.0, 1.5, -1.0]
Output: (0.55837, 0.666667)
Example 2
Input: r_chosen = [0.3], r_rejected = [0.3]
Output: (0.693147, 0.0)
Example 3
Input: r_chosen = [-500.0], r_rejected = [500.0]
Output: (1000.0, 0.0)
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
Hint 1
Only the difference between the chosen and rejected rewards matters, so work with d = r_chosen - r_rejected.
Hint 2
Compute d, take the mean of -log sigmoid(d) as the loss, and the accuracy is the share of pairs where d > 0.
Hint 3
Compute the loss stably with np.logaddexp(0, -d), which equals log(1 + exp(-d)) without overflow, and note that a tie (d == 0) does not count as correct.
Common mistakes
- The buggy version rewards the wrong direction.
Understand the idea
A reward model learns from pairs where a human preferred one response over another. The Bradley-Terry model says the chance the chosen one wins is sigmoid(r_chosen - r_rejected). Training minimises the negative log of that, so the loss falls as the chosen reward rises above the rejected one. Only the difference matters, so adding a constant to all rewards changes nothing.
r_chosen = [2, 0], r_rejected = [0, 1]. Differences [2, -1]. Pair 1: -log sigmoid(2) = 0.127. Pair 2: -log sigmoid(-1) = log(1 + e) = 1.313. Mean loss = 0.720. Accuracy = fraction with chosen > rejected = 1 / 2 = 0.5. For stability compute -log sigmoid(d) as log(1 + exp(-d)) in a form that never overflows, for example max(-d, 0) + log1p(exp(-|d|)).
loss = mean(-log sigmoid(r_c - r_r)); accuracy = mean(r_c > r_r)
RLHF reward models for chat assistants are trained with this loss.
Topics
Companies1
- DeepMind the topic appears in interview reports Google DeepMind interview guide (landedjobs/ai-interview-guides)
From public interview reports and guides. Not affiliated with or endorsed by these companies.