AI Wiki中文/EN

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.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A 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.

Exact policy gradients approach a known optimum, with the finite-step residual kept visible.
Exact policy gradients approach a known optimum, with the finite-step residual kept visible.

Separate the label, the reward and the policy

In a sequential environment, a comparison can concern an entire trajectory segment. With observations oto_t and actions ata_t, a simple predicted segment score is:

Rϕ(τ)=∑t∈τrϕ(ot,at).R_\phi(\tau)=\sum_{t\in\tau}r_\phi(o_t,a_t).

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 yy conditioned on its prompt xx.

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 σ(z)=1/(1+e−z)\sigma(z)=1/(1+e^{-z}):

Pϕ(A≻B∣x)=σ(rϕ(x,A)−rϕ(x,B)).P_\phi(A\succ B\mid x)=\sigma(r_\phi(x,A)-r_\phi(x,B)).

For comparison nn, let tn∈[0,1]t_n\in[0,1] 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:

LR=−1N∑n=1N[tnlog⁡pn+(1−tn)log⁡(1−pn)].\mathcal L_R=-\frac1N\sum_{n=1}^N[t_n\log p_n+(1-t_n)\log(1-p_n)].

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 qi>0q_i>0 be a reference policy over KK answers, and pip_i the policy to learn. With β>0\beta>0, a widely used regularized objective is:

J(p)=∑i=1Kpiri−β∑i=1Kpilog⁡piqi,∑ipi=1.J(p)=\sum_{i=1}^Kp_i r_i-\beta\sum_{i=1}^Kp_i\log\frac{p_i}{q_i},\qquad \sum_i p_i=1.

The second term penalizes DKL(p∥q)D_{\mathrm{KL}}(p\Vert q). 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 β\beta.

Using a Lagrange multiplier for normalization, the derivative with respect to pip_i yields log⁡(pi/qi)=ri/β\log(p_i/q_i)=r_i/\beta plus a constant. Normalizing gives:

pi∗=qieri/β∑jqjerj/β.p_i^*=\frac{q_i e^{r_i/\beta}}{\sum_j q_j e^{r_j/\beta}}.

The program evaluates this as a softmax of log⁡q+r/β\log q+r/\beta. 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 zz, with p=softmax⁡(z)p=\operatorname{softmax}(z). Define ai=ri−βlog⁡(pi/qi)a_i=r_i-\beta\log(p_i/q_i). Differentiating the full finite expectation gives:

∂J∂zi=pi(ai−∑jpjaj).\frac{\partial J}{\partial z_i}=p_i\left(a_i-\sum_jp_j a_j\right).

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:

J(p∗)−J(p)=βDKL(p∥p∗).J(p^*)-J(p)=\beta D_{\mathrm{KL}}(p\Vert p^*).

Substitute the expression for log⁡p∗\log p^* 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 log⁡4\log4, log⁡4\log4 and log⁡16\log16. The learned centered reward is approximately (log⁡4,0,−log⁡4)(\log4,0,-\log4).

"""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 β=1\beta=1, the exact answer is (96,12,1)/109; the trained policy’s maximum probability error is about 2.70×10−82.70\times10^{-8}. At β=2\beta=2, the error is about 2.15×10−162.15\times10^{-16}. At β=0.5\beta=0.5, it remains about 5.586×10−45.586\times10^{-4}: the tiny third-action probability converges slowly under these logits and step size. The report keeps this residual visible.

Reward fitting takes O(N+K)O(N+K) work per full update for NN pairs and KK tabular scores; a policy update takes O(K)O(K) 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

  1. A beats B with probability 0.8. What reward difference does the basic model imply?

Answer: The odds are 0.8/0.2=40.8/0.2=4, so rA−rB=log⁡4r_A-r_B=\log4. This is a model-based scale, not a unit of human happiness.

  1. Add 20 to every reward. Does the optimal policy change?

Answer: No. The common factor e20/βe^{20/\beta} cancels from normalization. The objective value increases by 20, but comparisons and the optimizer are unchanged.

  1. For q=(0.6,0.3,0.1)q=(0.6,0.3,0.1) and reward (log⁡4,0,−log⁡4)(\log4,0,-\log4), derive the optimum at β=1\beta=1.

Answer: Unnormalized weights are (2.4,0.3,0.025)(2.4,0.3,0.025). Their sum is 2.725, giving (96,12,1)/109(96,12,1)/109. This provides an independent check on gradient ascent.

  1. 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?

Choose one answer

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

  1. Deep Reinforcement Learning from Human Preferences — v1
    Paul F. Christiano; Jan Leike; Tom B. Brown; Miljan Martic; Shane Legg; Dario Amodei · 2017
  2. 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
  3. 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:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.