RLHF: preferences teach a reward, then a policy
人类反馈强化学习
Follow a three-response training loop and compare finite-step policy gradients with an exact KL-regularized optimum.
rlhfA person chooses an answer; the policy still needs a learning signal
Suppose a system can give three answers, A, B and C. A reviewer can choose between two answers without supplying a numeric score for each. A reward model turns those comparisons into scores; a policy then changes how often it produces each answer. These are different learning problems. The policy can become very good at maximizing the score even when the score misses what the reviewer wanted.
Reinforcement learning from human feedback, or RLHF, uses human feedback to guide reinforcement learning. Pairwise preference learning is a common form, not its only possible definition. Christiano and colleagues, section 2.2, alternate trajectory generation, human comparisons and reward fitting in simulated control and Atari. Their policy algorithms include TRPO and A2C. Stiennon and colleagues, section 3, adapt a comparison–reward–policy pipeline to summarization, starting from a supervised language model and using PPO. RLHF does not always mean PPO, and it did not begin as a synonym for chatbot training.
Our experiment has three possible responses and invented preference frequencies. It actually fits a reward and trains a policy, while remaining small enough to calculate the optimum. It uses no human study, pretrained language model or PPO implementation.
Separate the label, the reward and the policy
In a sequential environment, a comparison can concern an entire trajectory segment. With observations and actions , a simple predicted segment score is:
This undiscounted sum follows the basic comparison model in Christiano, section 2.2.3. Changing segment length, discounting or reward normalization changes its meaning. For language generation, a scalar model can instead score a complete response conditioned on its prompt .
A common comparison assumption is Bradley–Terry: the probability that answer A is preferred to B depends on their score difference, not their absolute scores. Write :
For comparison , let be the target probability assigned to its first candidate. A binary label is a special case; a tie or aggregated comparison frequency can be soft. The mean negative log-likelihood is:
The sign matters: minimizing this loss rewards accurate predictions. The program evaluates it with logaddexp to avoid overflow. It uses the basic logistic model, not Christiano’s full ensemble, query-selection and random-response mixture recipe. It also omits incomparability: an unanswerable comparison should not automatically become a tie.
Now freeze the fitted reward. For a fixed prompt, let be a reference policy over answers, and the policy to learn. With , a widely used regularized objective is:
The second term penalizes . Stiennon, section 3.4, implements a reference-probability penalty at the sequence level; Rafailov and colleagues, sections 3–4, give this objective and its closed-form optimum. KL discourages unrestricted movement but does not guarantee accurate or acceptable behavior. Reward scaling also changes the effective strength of a fixed .
Using a Lagrange multiplier for normalization, the derivative with respect to yields plus a constant. Normalizing gives:
The program evaluates this as a softmax of . The reference must cover all considered answers. A zero reference probability is excluded here; finite KL cannot assign positive probability outside its support.
Rather than replacing training with this oracle, we optimize logits , with . Define . Differentiating the full finite expectation gives:
The extra constant from differentiating the entropy cancels because the softmax Jacobian sums to zero. This is an exact, enumerated policy gradient. A language model cannot normally enumerate every possible response; sampled policy-gradient methods address a different computational regime.
There is also an exact check on any candidate distribution:
Substitute the expression for to verify the identity. It tests the objective and the optimum together, and quantifies a finite-step optimization gap without pretending training has converged.
Train the reward, then compare a policy with the oracle
Run the complete program with Python and NumPy. Pair order is (A,B), (B,C), (A,C); authored targets are 0.8, 0.8, 16/17. They correspond to reward differences , and . The learned centered reward is approximately .
"""Original three-response preference-to-policy loop; exact expectations, not PPO."""
import json
import numpy as np
def sigmoid(x):
x = np.asarray(x, dtype=float)
return np.exp(-np.logaddexp(0, -x))
def softmax(x):
x = np.asarray(x, dtype=float)
if x.ndim != 1 or not len(x) or not np.isfinite(x).all():
raise ValueError("Expected a nonempty finite vector")
e = np.exp(x - x.max())
return e / e.sum()
def preferences(scores, pairs):
return sigmoid(scores[pairs[:, 0]] - scores[pairs[:, 1]])
def pair_loss_grad(scores, pairs, targets):
scores = np.asarray(scores, dtype=float)
pairs = np.asarray(pairs, dtype=int)
targets = np.asarray(targets, dtype=float)
if (scores.ndim != 1 or pairs.ndim != 2 or pairs.shape[1] != 2
or len(pairs) == 0 or targets.shape != (len(pairs),)
or not np.isfinite(scores).all() or not np.isfinite(targets).all()
or np.any((targets < 0) | (targets > 1))
or pairs.min() < 0 or pairs.max() >= len(scores)):
raise ValueError("Invalid scores, pairs or soft labels")
delta = scores[pairs[:, 0]] - scores[pairs[:, 1]]
loss = np.mean(np.logaddexp(0, delta) - targets * delta)
residual = (sigmoid(delta) - targets) / len(pairs)
gradient = np.zeros_like(scores)
np.add.at(gradient, pairs[:, 0], residual)
np.add.at(gradient, pairs[:, 1], -residual)
return float(loss), gradient
def fit_scores(pairs, targets, size=3, steps=2000):
scores = np.zeros(size)
for _ in range(steps):
_, gradient = pair_loss_grad(scores, pairs, targets)
scores -= 0.5 * gradient
return scores
def policy_for_reward(reference, reward, beta):
reference = np.asarray(reference, dtype=float)
reward = np.asarray(reward, dtype=float)
if (reference.ndim != 1 or reference.shape != reward.shape
or not np.isfinite(reference).all() or not np.isfinite(reward).all()
or np.any(reference <= 0) or not np.isclose(reference.sum(), 1)
or not np.isfinite(beta) or beta <= 0):
raise ValueError("Positive normalized reference and beta are required")
return softmax(np.log(reference) + reward / beta)
PAIRS = np.array([[0, 1], [1, 2], [0, 2]])
def objective_grad(logits, reference, reward, beta):
# Validation and oracle share the same domain, not the optimizer.
policy_for_reward(reference, reward, beta)
p = softmax(logits)
logp = logits - np.logaddexp.reduce(logits)
advantage = reward - beta * (logp - np.log(reference))
value = p @ advantage
return float(value), p * (advantage - value)
def train_policy(reference, reward, beta, steps=3000):
logits = np.log(reference)
trace = []
for step in range(steps+1):
value, gradient = objective_grad(logits, reference, reward, beta)
if step % 300 == 0: trace.append([step, value])
if step < steps: logits += .3 * gradient
return softmax(logits), trace
def demo():
reference = np.array([.6, .3, .1])
# Authored fractional preference frequencies, not collected human labels.
targets = np.array([.8, .8, 16/17])
reward = fit_scores(PAIRS, targets)
results = []
for beta in [2., 1., .5]:
policy, trace = train_policy(reference, reward, beta)
oracle = policy_for_reward(reference, reward, beta)
results.append(dict(beta=beta, policy=policy.tolist(), oracle=oracle.tolist(),
max_error=float(np.max(abs(policy-oracle))),
expected_reward=float(policy@reward),
kl=float(policy@np.log(policy/reference)), trace=trace))
return dict(reference=reference.tolist(), targets=targets.tolist(),
learned_reward=reward.tolist(), results=results)
if __name__ == "__main__":
print(json.dumps(demo(), indent=2))
The reference is (0.6, 0.3, 0.1). Each policy receives 3,000 updates. At , the exact answer is (96,12,1)/109; the trained policy’s maximum probability error is about . At , the error is about . At , it remains about : the tiny third-action probability converges slowly under these logits and step size. The report keeps this residual visible.
Reward fitting takes work per full update for pairs and tabular scores; a policy update takes work and memory. The traces retain only every 300th step. These costs describe the finite teaching model, not transformer training or human annotation.
A correct optimizer can faithfully optimize the wrong score
This experiment separates two errors: learning an imperfect reward and failing to optimize that reward. Its synthetic probabilities were deliberately generated by the assumed logistic model, so the first problem is unusually easy. Real reviewers can disagree, preferences can depend on context, and new policy outputs can leave the comparison data’s coverage.
The reward model, policy and reference have distinct roles even when initialized from the same language model. Supervised fine-tuning supplies demonstrations; it does not by itself fit comparison preferences. PPO, when used, is an optimization algorithm rather than a definition of human values. A held-out comparison score and an independent evaluation of generated responses answer different questions.
No production result follows from the three-answer calculation. To evaluate a real pipeline, specify annotator instructions, data splits, reward calibration, policy sampling, reference and KL convention, and a fresh evaluation protocol. A small KL or decreasing reward loss alone is insufficient.
Check the three stages separately
- A beats B with probability 0.8. What reward difference does the basic model imply?
Answer: The odds are , so . This is a model-based scale, not a unit of human happiness.
- Add 20 to every reward. Does the optimal policy change?
Answer: No. The common factor cancels from normalization. The objective value increases by 20, but comparisons and the optimizer are unchanged.
- For and reward , derive the optimum at .
Answer: Unnormalized weights are . Their sum is 2.725, giving . This provides an independent check on gradient ascent.
- The fitted reward increases while fresh human evaluation worsens. Does a correct gradient rule out this outcome?
Answer: No. The gradient optimizes the fitted score and KL penalty. Reward misspecification or distribution shift can make that improvement diverge from human preferences; the optimizer’s correctness is not the reward model’s validity.
From trajectory feedback to language preferences
Christiano’s section 2.2 makes the feedback loop explicit; Stiennon’s section 3 shows a language-generation setting; Rafailov’s sections 3–4 expose the regularized mathematical objective and motivate an alternative parameterization. Read the companion reward-modeling article for identifiability and proxy failure, then DPO for direct preference optimization. Neither alternative removes the need to inspect whose judgments the labels represent.
Make a prediction, then check
Does maximizing a fitted reward guarantee human approval?
Learning objectives
- Separate comparison labels, learned reward and policy optimization.
- Verify the toy calculation and state what it cannot establish.
Prerequisites & connections
Explore related knowledge →References
- Deep Reinforcement Learning from Human Preferences — v1
Paul F. Christiano; Jan Leike; Tom B. Brown; Miljan Martic; Shane Legg; Dario Amodei · 2017 - Learning to summarize from human feedback — v1
Nisan Stiennon; Long Ouyang; Jeff Wu; Daniel M. Ziegler; Ryan Lowe; Chelsea Voss; Alec Radford; Dario Amodei; Paul F. Christiano · 2020 - Direct Preference Optimization: Your Language Model is Secretly a Reward Model — v2
Rafael Rafailov; Archit Sharma; Eric Mitchell; Stefano Ermon; Christopher D. Manning; Chelsea Finn · 2023
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author. Section2.2 through2.2.4 opening; PDF5 viewed: trajectory comparisons, soft labels, negative cross-entropy and actual recipe modifications. Sections3.1/3.4; PDF5/6 viewed. SFT/comparison/reward/PPO and KL penalty. Printed positive log-sigmoid loss sign is not copied as a minimization objective; see research note. Sections3/4, PDF3/4 viewed; gradient and procedure text read. BT, KL objective, partition cancellation and DPO; v2 dated2023-12-13. Seven paired equations and four explained exercises. Finite exact-expectation policy gradients, all-logit finite differences, KL gap identity and known optimum; beta0.5 finite-step residual retained. Synthetic labels, no PPO or human-feedback collection.
- Finite exact-expectation policy gradients, all-logit finite differences, KL gap identity and known optimum; beta0.5 finite-step residual retained. Synthetic labels, no PPO or human-feedback collection.
- Four computed SVG variants per topic;10 numeric/geometry tests and30 responsive cases passed. Ten selected final captures directly viewed. Full article acceptance recorded separately.
Source locations checked:
- Deep Reinforcement Learning from Human Preferences — v1 · Section2.2 through2.2.4 opening; PDF5 viewed: trajectory comparisons, soft labels, negative cross-entropy and actual recipe modifications.
- Learning to summarize from human feedback — v1 · Sections3.1/3.4; PDF5/6 viewed. SFT/comparison/reward/PPO and KL penalty. Printed positive log-sigmoid loss sign is not copied as a minimization objective; see research note.
- Direct Preference Optimization: Your Language Model is Secretly a Reward Model — v2 · Sections3/4, PDF3/4 viewed; gradient and procedure text read. BT, KL objective, partition cancellation and DPO; v2 dated2023-12-13.
Related topics