ch10_preferences.py
Companion code for Preferences, reward models, and the KL-regularised policy. Needs only Python 3 and NumPy: python code/ch10_preferences.py.
"""Chapter 10: preferences, Bradley-Terry reward models, KL-regularised policies, DPO.
A toy "response" space of K = 20 items with known true rewards. We simulate
noisy pairwise preferences from the Bradley-Terry model and then:
1. fit the reward by (ridge-penalised) maximum likelihood with Newton's method,
and report estimation error against the number of comparisons;
2. build the KL-regularised optimal policy pi_beta(y) ~ pi_ref(y) exp(rhat(y)/beta)
for several beta and compare proxy reward (under rhat) with true reward;
3. fit DPO directly on the same preferences (gradient descent on the policy
logits, started at the reference) and compare with the two-stage result.
NumPy only. Rewards are centred, because Bradley-Terry only identifies
differences.
"""
import numpy as np
K = 20
rng0 = np.random.default_rng(0)
R_TRUE = rng0.standard_normal(K)
R_TRUE -= R_TRUE.mean()
REF_LOGITS = 0.7 * rng0.standard_normal(K)
PI_REF = np.exp(REF_LOGITS - REF_LOGITS.max())
PI_REF /= PI_REF.sum()
REF_LOGITS = np.log(PI_REF) # normalised log-probabilities
LAM = 0.1 # ridge penalty (Gaussian prior on rewards) so the MLE exists on small data
def sigmoid(x):
return 1.0 / (1.0 + np.exp(-x))
def simulate(n, rng):
"""n comparisons between uniformly drawn distinct items. Returns (winner, loser)."""
i = rng.integers(K, size=n)
j = (i + rng.integers(1, K, size=n)) % K
i_wins = rng.random(n) < sigmoid(R_TRUE[i] - R_TRUE[j])
return np.where(i_wins, i, j), np.where(i_wins, j, i)
def fit_bt(w, l, lam=LAM, iters=50):
"""Newton's method for the penalised Bradley-Terry log-likelihood."""
r = np.zeros(K)
for _ in range(iters):
p = sigmoid(r[w] - r[l]) # P(observed winner wins)
grad = np.zeros(K)
np.add.at(grad, w, 1 - p)
np.add.at(grad, l, -(1 - p))
grad -= lam * r
H = lam * np.eye(K) # negative Hessian
c = p * (1 - p)
np.add.at(H, (w, w), c)
np.add.at(H, (l, l), c)
np.add.at(H, (w, l), -c)
np.add.at(H, (l, w), -c)
r = r + np.linalg.solve(H, grad)
return r - r.mean()
def tilted(rhat, beta):
"""KL-regularised optimum: pi(y) proportional to pi_ref(y) exp(rhat(y)/beta)."""
z = np.log(PI_REF) + rhat / beta
z -= z.max()
p = np.exp(z)
return p / p.sum()
def kl(p, q):
m = p > 0
return float((p[m] * np.log(p[m] / q[m])).sum())
def fit_dpo(w, l, beta, steps=400, c=2.0):
"""DPO: minimise -mean log sigmoid(beta[(phi_w - ref_w) - (phi_l - ref_l)]) over
policy logits phi, started at the reference. Step size c / beta^2 so the implicit
reward beta (phi - ref) moves at a rate that does not depend on beta."""
phi = REF_LOGITS.copy()
n = len(w)
for _ in range(steps):
m = beta * ((phi[w] - REF_LOGITS[w]) - (phi[l] - REF_LOGITS[l]))
g = beta * sigmoid(-m) / n # d loss / d phi_w = -g, d phi_l = +g
grad = np.zeros(K)
np.add.at(grad, w, -g)
np.add.at(grad, l, g)
phi -= (c / beta**2) * grad * K
p = np.exp(phi - phi.max())
return p / p.sum()
def centred(x):
return x - x.mean()
def experiment_error():
print("1. Bradley-Terry fit: estimation error vs number of comparisons (100 repetitions)")
print("%6s %10s %12s %14s" % ("n", "RMSE", "corr(r,rhat)", "argmax correct"))
for n in (20, 50, 100, 200, 500, 2000):
rmse, cor, top = [], [], []
for rep in range(100):
rng = np.random.default_rng(10_000 + rep)
rhat = fit_bt(*simulate(n, rng))
rmse.append(np.sqrt(np.mean((rhat - R_TRUE) ** 2)))
cor.append(np.corrcoef(rhat, R_TRUE)[0, 1])
top.append(np.argmax(rhat) == np.argmax(R_TRUE))
print("%6d %10.3f %12.3f %14.2f" % (n, np.mean(rmse), np.mean(cor), np.mean(top)))
print("(true reward sd across items: %.3f; best item has reward %.3f)" %
(R_TRUE.std(), R_TRUE.max()))
def experiment_overopt():
betas = [np.inf, 3.0, 1.0, 0.3, 0.1, 0.03, 0.01]
print("\n2. KL-regularised policy under the estimated reward (mean over 200 repetitions)")
print(" true reward of the best item: %.3f; of the reference policy: %.3f" %
(R_TRUE.max(), PI_REF @ R_TRUE))
for n in (50, 500):
print(" n = %d comparisons" % n)
print(" %6s %8s %8s %8s %8s %12s" %
("beta", "KL", "proxy", "true", "gap", "P(<beta=1)"))
res = {b: [] for b in betas}
for rep in range(200):
rng = np.random.default_rng(20_000 + rep)
rhat = fit_bt(*simulate(n, rng))
for b in betas:
p = PI_REF if np.isinf(b) else tilted(rhat, b)
res[b].append((kl(p, PI_REF), p @ rhat, p @ R_TRUE))
ref_true = np.array([r[2] for r in res[1.0]]) # true reward at beta = 1, per repetition
for b in betas:
kl_, proxy, true = np.mean(res[b], axis=0)
worse = np.mean(np.array([r[2] for r in res[b]]) < ref_true - 1e-12)
print(" %6s %8.3f %8.3f %8.3f %8.3f %12.2f" %
("inf" if np.isinf(b) else "%.2f" % b, kl_, proxy, true, proxy - true, worse))
def experiment_dpo():
print("\n3. DPO vs two-stage (BT fit, then tilt), same preferences, n = 200, 100 repetitions")
print("%6s | %-26s | %-26s | %8s" % ("beta", "two-stage KL / true", "DPO KL / true", "mean TV"))
for beta in (1.0, 0.3, 0.1):
a, b, tv = [], [], []
for rep in range(100):
rng = np.random.default_rng(30_000 + rep)
w, l = simulate(200, rng)
p2 = tilted(fit_bt(w, l), beta)
pd = fit_dpo(w, l, beta)
a.append((kl(p2, PI_REF), p2 @ R_TRUE))
b.append((kl(pd, PI_REF), pd @ R_TRUE))
tv.append(0.5 * np.abs(p2 - pd).sum())
a, b = np.mean(a, 0), np.mean(b, 0)
print("%6.2f | %12.3f %12.3f | %12.3f %12.3f | %8.3f" % (beta, a[0], a[1], b[0], b[1], np.mean(tv)))
if __name__ == "__main__":
experiment_error()
experiment_overopt()
experiment_dpo()