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.
def reward_loss(r_chosen, r_rejected)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. Worked example: 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|)). Rule: 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.