Overview
It is hard to write down a rule for a "good answer", but people can easily say which of two answers is better. RLHF turns many of those comparisons into a reward model, a learned judge. It then trains the language model to score well with that judge without drifting too far from how it wrote before.
A short history
Learning a reward from human comparisons was shown to work for deep reinforcement learning by Paul Christiano and colleagues in 2017, on simulated robots and Atari. OpenAI applied the same recipe to language models, and the 2022 InstructGPT paper by Long Ouyang and colleagues set the three-step form used since: supervised fine-tuning, a reward model, then PPO. It became the standard way to align chat models with what people prefer.
How it works
- Supervised fine-tuning (SFT): fine-tune a base model on example prompts with good responses.
- Collect preferences: for each prompt, sample two or more responses and have people pick the better one.
- Train a reward model that gives the preferred response a higher score.
- Optimize the policy (usually with PPO) to maximize reward, with a KL penalty that keeps it close to the SFT model.
Watch out for
- Reward hacking: the policy finds quirks the reward model likes, such as length or flattery, that people do not.
- Noisy or inconsistent labelers produce a noisy reward model.
- PPO is costly and finicky. DPO (Direct Preference Optimization) trains straight on the preference pairs with no separate reward model or RL loop.
Use cases
When to use it
The quality you want (helpful, safe, on-brand) is easy to judge but hard to specify as labels or rules.
In industry
- Conversational assistants
- Tuning a chat model so its answers are more helpful and follow instructions, using rankings from human raters.
- Customer service
- Shaping a support assistant toward answers agents judge correct and appropriately worded for the company.
- Content safety
- Steering a model away from responses reviewers mark as harmful when the boundary is hard to write as rules.
Choosing it: what must hold
- A model that is already fine-tuned and produces reasonable answers.
- People who can compare answers consistently, with written guidelines.
- Budget for a reinforcement learning loop and for checking the reward model against fresh human judgments.
When to choose something else
| If | Use instead |
|---|---|
| You want to train directly on the preference pairs | DPO (Direct Preference Optimization) |
| You have good example answers and no comparisons | Supervised fine-tuning alone |
Math foundations
How a preference is modelled
The Bradley-Terry model: the chance a person prefers one response over another depends only on the difference between their reward scores.
Reward model loss
Reward model loss on a preferred () versus rejected () pair. It is the negative log-likelihood of the human's choice under the model above, so minimizing it pushes the preferred response's score above the rejected one's.
Policy objective
Policy objective, with controlling how far the model may drift. The first term asks for responses the judge scores highly; the second charges for every bit the new policy differs from the SFT model.
Symbols
- a prompt
- the response a person preferred, and the one they rejected
- the reward model's score for a response
- the policy being trained (the language model)
- the reference policy, the SFT model
- weight of the KL penalty
- the sigmoid function
Worked by hand
The reward model scores a preferred response at 1.5 and the rejected one at 0.5.
The model already agrees with the person with probability 0.73, so the loss is small. If the scores were swapped the probability would be 0.27 and the loss 1.313.
Visual example
Loading the example.
Try this
- Drop the comparisons to 10: the judge gets the order wrong and the tuned model follows it.
- Lower the drift penalty toward 0.1 and watch the model pile onto one answer.
- Click each stage to light the part of the pipeline it feeds.
Code sample
from impl import RLHF, PreferenceEnvironment
from config import RLHFConfig
env = PreferenceEnvironment(n_prompts=8, n_responses=6, n_features=5, seed=0) # features + simulated human
agent = RLHF(env.features, RLHFConfig(beta=0.5))
agent.sft(*env.demonstrations(400, agent.rng)) # (a) base policy
human = lambda x, a, b: env.human_prefers_first(x, a, b, agent.rng)
prompts, winners, losers = agent.collect_preferences(human, n_pairs=800) # (b) comparisons
agent.fit_reward_model(prompts, winners, losers) # (c) reward model
agent.optimise_policy() # (d) KL-penalised policy gradient
print(env.expected_true_score(agent.reference_policy())) # hidden preference score of the SFT policy
print(env.expected_true_score(agent.policy())) # higher after RLHF
print(agent.kl_to_reference().mean()) # how far the policy movedRead the implementation (310 lines)
"""Reinforcement learning from human feedback (RLHF) on a toy categorical policy.
The four steps, as used to align language models, at toy size:
(a) Supervised fine-tuning (SFT): fit a base policy pi(y | x) to example prompt/response pairs.
(b) Collect preferences: for a prompt sample two responses from the policy, a human picks the better one.
(c) Reward model: train r(x, y) so the preferred response scores higher,
L_RM = -log sigmoid(r(x, y_w) - r(x, y_l))
(d) Policy optimisation: raise the reward while staying close to the SFT reference policy,
maximise E_{y ~ pi}[r(x, y)] - beta * KL(pi(. | x) || pi_ref(. | x))
Here prompts and responses are discrete ids. The policy is tabular: one row of logits per prompt, softmax over
the responses. Every (prompt, response) pair has a feature vector; the reward model (linear, or one tanh layer)
reads those features. The "human" is `PreferenceEnvironment`, which holds a hidden true preference score and
answers comparisons with seeded noise. Step (d) is a plain KL-penalised policy gradient (REINFORCE with a
baseline for the reward term, the KL term in closed form), not PPO. NumPy only.
"""
from __future__ import annotations
import numpy as np
try:
from .config import RLHFConfig
except ImportError: # run from the template's own folder
from config import RLHFConfig
def _sigmoid(x: np.ndarray) -> np.ndarray:
return 0.5 * (1.0 + np.tanh(0.5 * x))
def _softmax(logits: np.ndarray) -> np.ndarray:
z = logits - logits.max(axis=-1, keepdims=True)
p = np.exp(z)
return p / p.sum(axis=-1, keepdims=True)
def _log_softmax(logits: np.ndarray) -> np.ndarray:
z = logits - logits.max(axis=-1, keepdims=True)
return z - np.log(np.exp(z).sum(axis=-1, keepdims=True))
class PreferenceEnvironment:
"""The world outside the learner: features of every response, and a simulated human.
features: shape (P, R, F), the feature vector of response y to prompt x. The learner may read these.
true_scores: shape (P, R), the hidden preference score. Only the simulated human (and tests) read it:
a linear part plus a tanh part of the features, so it is not exactly linear.
n_prompts P, n_responses R, n_features F size the toy problem. noise is the temperature of the human's
choice: 0 always picks the truly better response, larger values make mistakes more likely.
"""
def __init__(self, n_prompts: int = 8, n_responses: int = 6, n_features: int = 5, noise: float = 1.0,
seed: int = 0) -> None:
if n_prompts < 1 or n_responses < 2 or n_features < 1:
raise ValueError("need at least 1 prompt, 2 responses and 1 feature")
if noise < 0:
raise ValueError(f"noise must be 0 or more, got {noise}")
rng = np.random.default_rng(seed)
self.features = rng.normal(size=(n_prompts, n_responses, n_features))
w_linear = rng.normal(size=n_features)
w_curved = rng.normal(size=n_features)
self.true_scores = self.features @ w_linear + np.tanh(self.features @ w_curved)
self.noise = float(noise)
def demonstrations(self, n: int, rng: np.random.Generator, quality: float = 0.3):
"""Example prompt/response pairs from an imperfect demonstrator, for supervised fine-tuning.
The demonstrator answers prompt x with response y with probability softmax(quality * true_scores[x]):
better than random, far from the best. Returns (prompts, responses), int arrays of shape (n,).
"""
probs = _softmax(quality * self.true_scores)
prompts = rng.integers(0, probs.shape[0], size=n)
cum = np.cumsum(probs[prompts], axis=1)
responses = np.minimum((rng.random(n)[:, None] > cum).sum(axis=1), probs.shape[1] - 1)
return prompts, responses
def human_prefers_first(self, prompts, first, second, rng: np.random.Generator) -> np.ndarray:
"""The simulated human compares two responses per prompt. Returns a bool array: True = first is better.
P(first) = sigmoid((true_score(first) - true_score(second)) / noise).
"""
prompts, first, second = np.asarray(prompts), np.asarray(first), np.asarray(second)
diff = self.true_scores[prompts, first] - self.true_scores[prompts, second]
if self.noise == 0:
return diff > 0
return rng.random(len(diff)) < _sigmoid(diff / self.noise)
def expected_true_score(self, policy: np.ndarray) -> float:
"""Mean hidden preference score of responses sampled from a policy of shape (P, R)."""
return float((np.asarray(policy) * self.true_scores).sum(axis=1).mean())
class RLHF:
"""The learner. It sees `features` (shape (P, R, F)) and whatever data the steps hand it, never true scores.
logits: shape (P, R), the policy being trained. pi(y | x) = softmax(logits[x])[y].
ref_logits: shape (P, R), the frozen SFT reference policy (set by `sft`).
reward_params: weights of the reward model (set by `fit_reward_model`).
"""
def __init__(self, features: np.ndarray, config: RLHFConfig | None = None) -> None:
self.config = config or RLHFConfig()
self.features = np.asarray(features, dtype=float)
if self.features.ndim != 3:
raise ValueError(f"features must have shape (P, R, F), got {self.features.shape}")
self.n_prompts, self.n_responses, self.n_features = self.features.shape
self.rng = np.random.default_rng(self.config.seed)
self.logits = np.zeros((self.n_prompts, self.n_responses))
self.ref_logits: np.ndarray | None = None
hidden = self.config.reward_hidden
if hidden == 0:
self.reward_params = {"w": np.zeros(self.n_features)}
else:
self.reward_params = {
"W1": self.rng.normal(0.0, 1.0 / np.sqrt(self.n_features), size=(self.n_features, hidden)),
"b1": np.zeros(hidden),
"w2": self.rng.normal(0.0, 1.0 / np.sqrt(hidden), size=hidden),
}
self.history: dict[str, list[float]] = {"sft_loss": [], "reward_loss": [], "objective": []}
# ---- the policy -------------------------------------------------------------------------------------
def policy(self) -> np.ndarray:
"""pi(y | x) of the current policy, shape (P, R), rows sum to 1."""
return _softmax(self.logits)
def reference_policy(self) -> np.ndarray:
"""pi_ref(y | x), the frozen SFT policy, shape (P, R)."""
self._require_reference()
return _softmax(self.ref_logits)
def _require_reference(self) -> None:
if self.ref_logits is None:
raise RuntimeError("run sft first: it sets the reference policy")
def sample(self, prompts, policy: np.ndarray | None = None) -> np.ndarray:
"""One sampled response per prompt id in `prompts` (shape (n,)), from the current or the given policy."""
probs = (self.policy() if policy is None else np.asarray(policy))[np.asarray(prompts)]
cum = np.cumsum(probs, axis=1)
draws = (self.rng.random(len(probs))[:, None] > cum).sum(axis=1)
return np.minimum(draws, self.n_responses - 1)
# ---- (a) supervised fine-tuning ---------------------------------------------------------------------
def sft(self, prompts, responses) -> "RLHF":
"""Fit the policy to example pairs by gradient descent on the cross-entropy, then freeze a copy of it
as the reference policy.
prompts, responses: int arrays of shape (n,), response `responses[i]` was given to prompt `prompts[i]`.
Each prompt's row is fitted to that prompt's examples; a prompt with no example stays uniform.
"""
cfg = self.config
prompts, responses = np.asarray(prompts), np.asarray(responses)
counts = np.zeros((self.n_prompts, self.n_responses))
np.add.at(counts, (prompts, responses), 1.0)
totals = counts.sum(axis=1, keepdims=True)
seen = totals[:, 0] > 0
freq = np.divide(counts, totals, out=np.zeros_like(counts), where=totals > 0)
self.logits = np.zeros((self.n_prompts, self.n_responses))
for _ in range(cfg.sft_epochs):
log_pi = _log_softmax(self.logits)
self.history["sft_loss"].append(float(-(counts * log_pi).sum() / max(len(prompts), 1)))
grad = np.exp(log_pi) - freq # d (per-prompt mean cross-entropy) / d logits
grad[~seen] = 0.0
self.logits = self.logits - cfg.sft_learning_rate * grad
self.ref_logits = self.logits.copy()
return self
# ---- (b) preference collection ----------------------------------------------------------------------
def collect_preferences(self, human, n_pairs: int):
"""Sample two different responses per prompt from the current policy and ask the human which is better.
human: callable (prompts, first, second) -> bool array, True where the first response is preferred.
n_pairs: number of comparisons; prompts are drawn uniformly.
Returns (prompts, winners, losers), int arrays of shape (n_pairs,).
"""
prompts = self.rng.integers(0, self.n_prompts, size=n_pairs)
# Gumbel top-2: adding Gumbel noise to log-probabilities and taking the two largest samples two
# different responses, the first from pi and the second from pi with the first removed.
noisy = _log_softmax(self.logits)[prompts] + self.rng.gumbel(size=(n_pairs, self.n_responses))
top_two = np.argsort(-noisy, axis=1)[:, :2]
first, second = top_two[:, 0], top_two[:, 1]
first_wins = np.asarray(human(prompts, first, second), dtype=bool)
return prompts, np.where(first_wins, first, second), np.where(first_wins, second, first)
# ---- (c) the reward model ---------------------------------------------------------------------------
def _reward_forward(self, phi: np.ndarray, params: dict | None = None):
"""r for feature rows phi of shape (n, F). Returns (r of shape (n,), hidden activations or None)."""
params = self.reward_params if params is None else params
if "w" in params:
return phi @ params["w"], None
hidden = np.tanh(phi @ params["W1"] + params["b1"])
return hidden @ params["w2"], hidden
def reward(self, prompts, responses) -> np.ndarray:
"""Learned reward r(x, y) for prompt and response id arrays of shape (n,)."""
return self._reward_forward(self.features[np.asarray(prompts), np.asarray(responses)])[0]
def reward_table(self) -> np.ndarray:
"""Learned reward of every response to every prompt, shape (P, R)."""
flat = self.features.reshape(-1, self.n_features)
return self._reward_forward(flat)[0].reshape(self.n_prompts, self.n_responses)
def reward_loss_and_grads(self, prompts, winners, losers):
"""L_RM = mean of -log sigmoid(r(x, y_w) - r(x, y_l)), and its gradient for every reward parameter."""
prompts = np.asarray(prompts)
phi_w = self.features[prompts, np.asarray(winners)]
phi_l = self.features[prompts, np.asarray(losers)]
r_w, h_w = self._reward_forward(phi_w)
r_l, h_l = self._reward_forward(phi_l)
margin = r_w - r_l
loss = float(np.mean(np.logaddexp(0.0, -margin)))
d_margin = (_sigmoid(margin) - 1.0) / len(margin) # d loss / d r_w; d loss / d r_l is its negative
params = self.reward_params
if "w" in params:
return loss, {"w": (phi_w - phi_l).T @ d_margin}
grads = {"w2": (h_w - h_l).T @ d_margin}
d_pre_w = np.outer(d_margin, params["w2"]) * (1.0 - h_w**2)
d_pre_l = np.outer(-d_margin, params["w2"]) * (1.0 - h_l**2)
grads["W1"] = phi_w.T @ d_pre_w + phi_l.T @ d_pre_l
grads["b1"] = d_pre_w.sum(axis=0) + d_pre_l.sum(axis=0)
return loss, grads
def fit_reward_model(self, prompts, winners, losers) -> "RLHF":
"""Train the reward model on preference pairs with full-batch Adam.
prompts, winners, losers: int arrays of shape (n,), the human preferred `winners[i]` over `losers[i]`.
"""
cfg = self.config
m = {k: np.zeros_like(v) for k, v in self.reward_params.items()}
v = {k: np.zeros_like(v) for k, v in self.reward_params.items()}
for step in range(1, cfg.reward_epochs + 1):
loss, grads = self.reward_loss_and_grads(prompts, winners, losers)
self.history["reward_loss"].append(loss)
for name, g in grads.items():
m[name] = 0.9 * m[name] + 0.1 * g
v[name] = 0.999 * v[name] + 0.001 * g * g
m_hat, v_hat = m[name] / (1.0 - 0.9**step), v[name] / (1.0 - 0.999**step)
self.reward_params[name] = self.reward_params[name] - cfg.reward_learning_rate * m_hat / (
np.sqrt(v_hat) + 1e-8)
return self
def preference_accuracy(self, prompts, winners, losers) -> float:
"""Share of pairs where the reward model scores the preferred response higher."""
return float(np.mean(self.reward(prompts, winners) > self.reward(prompts, losers)))
# ---- (d) policy optimisation ------------------------------------------------------------------------
def kl_to_reference(self) -> np.ndarray:
"""KL(pi(. | x) || pi_ref(. | x)) for every prompt, shape (P,)."""
self._require_reference()
log_pi, log_ref = _log_softmax(self.logits), _log_softmax(self.ref_logits)
return (np.exp(log_pi) * (log_pi - log_ref)).sum(axis=1)
def objective(self, beta: float | None = None) -> np.ndarray:
"""E_{y ~ pi}[r(x, y)] - beta * KL(pi || pi_ref) for every prompt (exact, no sampling), shape (P,)."""
beta = self.config.beta if beta is None else beta
return (self.policy() * self.reward_table()).sum(axis=1) - beta * self.kl_to_reference()
def policy_gradient(self, beta: float | None = None, n_samples: int | None = None) -> np.ndarray:
"""Estimate d objective[x] / d logits[x] for every prompt, shape (P, R).
Reward term: the score-function (REINFORCE) estimate from n_samples responses sampled per prompt,
mean over samples of (r(x, y) - baseline) * (onehot(y) - pi), baseline = mean sampled reward.
KL term: exact, d KL / d logits = pi * (log pi - log pi_ref - KL).
"""
self._require_reference()
beta = self.config.beta if beta is None else beta
n_samples = self.config.policy_samples if n_samples is None else n_samples
log_pi, log_ref = _log_softmax(self.logits), _log_softmax(self.ref_logits)
pi = np.exp(log_pi)
rewards = self.reward_table()
cum = np.cumsum(pi, axis=1)
draws = (self.rng.random((self.n_prompts, n_samples))[:, :, None] > cum[:, None, :]).sum(axis=2)
draws = np.minimum(draws, self.n_responses - 1) # (P, n_samples)
counts = np.zeros_like(pi)
np.add.at(counts, (np.repeat(np.arange(self.n_prompts), n_samples), draws.ravel()), 1.0)
share = counts / n_samples # how often each response came up
baseline = (share * rewards).sum(axis=1, keepdims=True)
# mean of (r - b) * (onehot - pi): the onehot part is share * (r - b); the pi part is
# pi * mean(r - b), which is zero because b is the mean sampled reward.
grad_reward = share * (rewards - baseline)
log_ratio = log_pi - log_ref
kl = (pi * log_ratio).sum(axis=1, keepdims=True)
grad_kl = pi * (log_ratio - kl)
return grad_reward - beta * grad_kl
def optimise_policy(self, beta: float | None = None) -> "RLHF":
"""Gradient ascent on the KL-penalised objective, starting from the current logits.
beta overrides config.beta. The mean exact objective after every step goes to history["objective"].
"""
cfg = self.config
for _ in range(cfg.policy_steps):
self.logits = self.logits + cfg.policy_learning_rate * self.policy_gradient(beta)
self.history["objective"].append(float(self.objective(beta).mean()))
return self
def optimal_policy(self, beta: float | None = None) -> np.ndarray:
"""The exact maximiser of the objective for the current reward model, shape (P, R):
pi*(y | x) proportional to pi_ref(y | x) * exp(r(x, y) / beta). Useful to check the policy step."""
self._require_reference()
beta = self.config.beta if beta is None else beta
return _softmax(_log_softmax(self.ref_logits) + self.reward_table() / beta)
def run(self, environment: PreferenceEnvironment, n_demonstrations: int = 400, n_pairs: int = 800) -> "RLHF":
"""All four steps against an environment: SFT, collect preferences, fit the reward model, optimise."""
self.sft(*environment.demonstrations(n_demonstrations, self.rng))
human = lambda x, a, b: environment.human_prefers_first(x, a, b, self.rng) # noqa: E731
self.fit_reward_model(*self.collect_preferences(human, n_pairs))
return self.optimise_policy()- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Using Hugging Face TRL, run DPO on a small open model (around 0.5B-1B parameters) with a public preference dataset. Compare its answers with the SFT model's on 20 held-out prompts.
Check on learning
- The reward model is only ever trained on responses the SFT model produced. Why does that make reward hacking likely once the policy starts to change?
A way to think about it
Think about where the reward model's scores are trustworthy. As the policy moves, it produces responses unlike any the judge was trained on, and the judge's errors there are unchecked.
- Set to 0 and then to a very large value. Describe the model you get in each case.
A way to think about it
With no penalty the policy maximizes the judge's score alone. With a huge penalty any difference from the reference costs more than the reward can repay.
- The loss depends only on the difference between two scores. What does that imply about the absolute value of a reward, and does it matter for the policy step?
A way to think about it
Add a constant to every score and check the loss. Then look at whether a constant shift changes which responses the expectation in the policy objective favours.
- Two labelers disagree on 30% of pairs. How does that show up in the reward model, and what could you do about it before training?
A way to think about it
For a pair chosen both ways, the best the model can do is a score difference near zero. Consider measuring agreement, relabeling contested pairs, or giving clearer guidelines.