RLHF and Reward Learning Connections
Suppose you have a language model that predicts fluent text. But it has no notion of what a helpful or harmless answer looks like. There is no ground-truth reward function for "helpfulness" you can write down in closed form. Yet you still want to steer a policy toward behavior humans prefer. This is the central problem that Reinforcement Learning from Human Feedback (RLHF) solves. It converts subjective human judgments into a learned scalar reward signal. It then optimizes a policy against that signal using standard deep policy-gradient machinery. RLHF matters because it is the mechanism that turned raw autoregressive language models into usable assistants. It also generalizes far beyond text. Any domain where desired behavior is easy to recognize but hard to specify is a candidate. This includes dialogue quality, code style, robot motion aesthetics, and summarization fidelity. Such domains favor reward learning from preferences over hand-crafted rewards. The technique sits at the intersection of two ideas. These are covered in Imitation and Inverse Reinforcement Learning (recovering a reward function from behavioral signal) and Deep Policy Gradient Methods (optimizing a parametric policy against a scalar reward using gradient ascent). The big picture is a three-stage pipeline. First, supervised fine-tuning on demonstrations. Second, reward model training on human preference comparisons. Third, policy optimization (typically with PPO or a related algorithm) against the learned reward. This is usually regularized to stay close to the original model. Each stage has failure modes — reward hacking, distribution shift, mode collapse. These are well documented and must be understood, not just the happy path. This article gives the precise mechanics of the reward-modeling objective. It covers the RL fine-tuning loop, including the KL penalty that keeps the policy anchored. It explains the connection to inverse reinforcement learning. It also covers modern alternatives, such as Direct Preference Optimization, that skip explicit reward modeling. It closes with worked numerical traces and common failure modes. Finally, it traces the historical lineage from preference-learning theory to today's large-scale deployments.
- RLHF trains a reward model from pairwise human preferences, then optimizes a policy against it with RL, typically PPO with a KL penalty to a reference policy.
- The reward model is trained with a Bradley-Terry pairwise loss: it learns to score preferred completions higher than rejected ones, not to predict absolute scalar rewards.
- The RL fine-tuning stage maximizes expected reward minus a KL-divergence penalty, which prevents "reward hacking" and keeps outputs close to the base model's distribution.
- RLHF is a form of inverse reinforcement learning where the "expert" is a probabilistic preference model instead of demonstrated trajectories.
- Direct Preference Optimization (DPO) reformulates the same objective as a single supervised loss, avoiding the separate reward model and RL loop entirely.
- Reward hacking, reward model miscalibration, and policy collapse (mode-seeking degeneration) are the primary practical failure modes, mitigated by KL regularization, ensembling, and careful data curation.
RLHF replaces a hand-designed reward function with a learned model of human preferences, then uses policy-gradient RL — regularized to stay close to a reference policy — to optimize a language or control policy against that learned reward.
The idea
Reinforcement Learning from Human Feedback formalizes a setting where the reward function is unknown and unspecifiable, but comparisons between two outcomes are cheap for a human to make. Instead of asking a human to assign an absolute numeric reward to an output — a task humans are notoriously bad at doing consistently — RLHF asks a human (or a panel of annotators) to state a preference: "output A is better than output B." These pairwise preferences are then used to fit a reward model , a neural network that takes an input (a prompt) and a candidate output (a completion) and predicts a scalar score consistent with the observed preference ordering. The reward model is trained under the Bradley-Terry model of pairwise comparisons, which assumes the probability that a human prefers (the "winner") over (the "loser") given the same prompt is a logistic function of the reward difference:
where is the sigmoid function. This converts preference learning into a standard binary classification problem via maximum likelihood, and it is the same statistical model historically used to rank chess players (Bradley-Terry-Luce) and, before that, to model paired-comparison psychophysics data. Once the reward model is trained, it is frozen and used as a proxy environment reward for policy optimization. The policy — typically the same language model that was supervised-fine-tuned on demonstrations — is optimized to maximize expected reward under , using a policy-gradient algorithm such as Proximal Policy Optimization (PPO). Because is only an approximation of true human preference, and because policies optimized aggressively against a learned proxy tend to find degenerate high-scoring regions the proxy was never trained on (a failure called reward hacking or Goodhart's law in action), the RL objective adds a penalty term: the KL divergence between the current policy and a fixed reference policy (usually the supervised fine-tuned model before RL). The full objective per prompt is
The coefficient controls the tradeoff between reward maximization and staying close to the reference distribution: too small and the policy overfits to the reward model's blind spots; too large and the policy barely moves from its starting point. This structure is precisely why RLHF is best understood as a constrained inverse reinforcement learning problem: the reward is inferred from behavioral preference signal (as in IRL), but the "expert" is not a demonstrator producing trajectories — it is a comparison oracle producing rankings — and the resulting reward is used for standard forward RL with an explicit anchor to prevent divergence from plausible behavior.
How it works
The RLHF pipeline has three distinct stages, each of which can be studied and debugged independently.
Stage 1 — Supervised Fine-Tuning (SFT). Start from a pretrained base model and fine-tune it on a curated dataset of high-quality demonstrations (prompt, ideal-response pairs), using standard supervised cross-entropy loss. This gives an initial policy that is already reasonably well-behaved, dramatically narrowing the search space for later RL. This step is imitation learning in the sense of Imitation and Inverse Reinforcement Learning — behavioral cloning on expert demonstrations.
Stage 2 — Reward Model Training. Sample multiple completions from (or an earlier RLHF checkpoint) for a set of prompts. Have human annotators rank or pairwise-compare these completions. Fit by maximizing the log-likelihood of the observed preferences under the Bradley-Terry model.
Stage 3 — RL Fine-Tuning. Optimize (initialized from ) against the frozen reward model , using PPO (or another policy-gradient method), with a per-token or per-sequence KL penalty against . ```pseudocode
# ---------- Stage 1: Supervised Fine-Tuning ---------- function SFT(base_model, demonstration_data): pi_sft = base_model for (prompt, target_response) in demonstration_data: loss = CrossEntropy(pi_sft(prompt), target_response) pi_sft.parameters -= lr * gradient(loss, pi_sft.parameters) return pi_sft
# ---------- Stage 2: Reward Model Training ---------- function TRAIN_REWARD_MODEL(pi_sft, prompts, num_samples_k): comparisons = [] for x in prompts: candidates = [ pi_sft.sample(x) for i in 1..num_samples_k ] ranking = HUMAN_RANK(x, candidates) # human orders candidates for (y_w, y_l) in ALL_PAIRS_CONSISTENT_WITH(ranking): comparisons.append((x, y_w, y_l)) initialize r_phi (usually pi_sft backbone + scalar head) for batch in MINIBATCHES(comparisons): loss = 0 for (x, y_w, y_l) in batch: score_w = r_phi(x, y_w) score_l = r_phi(x, y_l) loss += -log( sigmoid(score_w - score_l) ) # Bradley-Terry NLL r_phi.parameters -= lr * gradient(loss / |batch|, r_phi.parameters) return r_phi
# ---------- Stage 3: RL Fine-Tuning (PPO against r_phi) ---------- function RLHF_PPO(pi_sft, r_phi, prompts, beta, epochs): pi_theta = COPY(pi_sft) # trainable policy pi_ref = FREEZE(pi_sft) # fixed anchor for KL penalty value_fn = initialize_value_network() for iteration in 1..epochs: batch = [] for x in SAMPLE(prompts): y = pi_theta.sample(x) # rollout, token by token r_env = r_phi(x, y) # scalar reward at end of sequence kl = SUM_OVER_TOKENS( log(pi_theta(y_t | x, y_
- log(pi_ref(y_t | x, y_
r_total = r_env - beta * kl # KL-regularized reward batch.append( (x, y, r_total) )
# standard PPO update using r_total as the trajectory reward advantages = COMPUTE_GAE(batch, value_fn) for epoch in 1..ppo_inner_epochs: ratio = pi_theta.prob(actions) / pi_theta_old.prob(actions) clipped = CLIP(ratio, 1 - eps, 1 + eps) advantages policy_loss = -MEAN( MIN(ratio advantages, clipped) ) value_loss = MSE(value_fn(states), returns) pi_theta.parameters -= lr gradient(policy_loss, pi_theta.parameters) value_fn.parameters -= lr gradient(value_loss, value_fn.parameters) pi_theta_old = COPY(pi_theta) return pi_theta ``` The reward model architecture is usually the same transformer backbone as the policy, with the final unembedding layer replaced by a single scalar head that reads the representation at the last token of the sequence. This scalar head is the only newly initialized component; the backbone is initialized from the SFT checkpoint so that the reward model starts with strong language understanding.
Complexity & correctness
Reward model training complexity. If there are prompts each with sampled completions ranked by humans, a full ranking of items induces up to pairwise comparisons; in practice implementations use only the adjacent comparisons from the ranking or a sampled subset to keep training cost linear in . Each forward/backward pass costs the same as one transformer forward pass, for sequence length and hidden dimension (attention plus feedforward costs), so total reward-model training cost is per epoch, identical in order to ordinary supervised fine-tuning at the same data scale. Space cost is one model checkpoint plus optimizer state, same as any transformer fine-tune — no combinatorial blowup, because comparisons are trained as independent binary-classification examples rather than requiring joint ranking inference.
RL fine-tuning complexity. Each PPO iteration requires: (1) a rollout phase, sampling sequences of length up to from , costing sequential decoding steps each (this autoregressive sampling dominates wall-clock time in practice), (2) a reward-model forward pass per sample, , (3) a KL computation requiring a forward pass of on the same sequences, same order, and (4) several epochs of PPO gradient updates over the collected batch, each . So the RL stage requires four models resident simultaneously — policy, reference policy, reward model, and value function — which is the dominant memory cost relative to plain fine-tuning, typically 3–4× the memory footprint of the base model alone (a major practical driver toward memory-efficient variants and DPO-style methods that eliminate the explicit reward model and PPO loop).
Correctness argument — why the Bradley-Terry loss recovers a valid reward ordering. The maximum-likelihood estimator for the Bradley-Terry model is consistent: if preferences are genuinely generated by some latent reward function under the logistic-comparison assumption, then as the number of independent comparisons grows, up to a global additive constant and positive scaling, because the Bradley-Terry log-likelihood is a strictly concave function of the reward differences and its unique maximizer (given enough connected comparisons spanning the completion space) coincides with the true parameter under standard M-estimation theory. The additive-constant/scale ambiguity is harmless for RL: policy gradients under and under for define the same ordering of expected returns and hence (ignoring the interaction with the KL term's fixed weighting) similar optimal policies, though in practice the scale interacts with and must be tuned jointly.
Correctness argument — why the KL penalty is necessary, not optional. Without regularization, the RL objective is simply . Because is trained only on the support of completions the SFT/annotated policy actually produced, it is unconstrained (and potentially arbitrarily miscalibrated) outside that support. An unconstrained policy-gradient optimizer will drift toward regions of output space that maximize 's score even if those regions are degenerate, repetitive, or nonsensical to a human — this is reward hacking, a direct instance of Goodhart's law ("when a measure becomes a target, it ceases to be a good measure"). The KL term upper-bounds how far the induced output distribution can move from the well-understood reference distribution; formally, the regularized objective has the closed-form optimal solution
which is a tilted (reweighted) version of the reference policy rather than an unconstrained maximizer — this closed form is exactly the bridge exploited by Direct Preference Optimization, which substitutes it back into the Bradley-Terry loss to eliminate the RL loop analytically.
Honest tradeoffs. PPO-based RLHF is sample-inefficient (many rollouts per gradient step), sensitive to and learning-rate schedules, and requires nontrivial infrastructure (four models in memory, reward-model reward hacking monitoring, KL-divergence tracking). Its benefit is that it directly optimizes the thing you actually want (expected discounted reward under sequential decisions), which matters when responses are multi-turn or when the reward is genuinely sequential rather than a single terminal judgment. Simpler alternatives like DPO trade this generality for stability and much lower engineering cost, at the price of being provably equivalent only under the same Bradley-Terry assumptions and losing some flexibility for multi-step or non-bandit reward structures.
Worked example
Consider a toy setting: prompt "Summarize: The cat sat on the mat." Suppose the SFT policy generates two candidate completions:
- = "A cat sat on a mat." (accurate, concise)
- = "The cat, feline creature of legend, took its throne upon the mat, as cats do." (verbose, off-tone)
A human annotator prefers . Suppose the reward model, before this example is used in training, currently scores and (miscalibrated — it currently prefers the wrong one).
Reward model gradient step. The Bradley-Terry loss for this single pair is:
Numerically, , so . The gradient with respect to is , pushing up, and symmetrically pushing down. After many such updates across the dataset, the reward model learns to assign higher scores to concise, accurate summaries.
RL step with the trained reward model. Suppose after reward-model training, and . Suppose the policy , currently close to , assigns probability to sequences resembling -style completions and to -style ones, with assigning the same probabilities initially (KL ). Take .
| Quantity | (concise) | (verbose) |
|---|---|---|
| 0.90 | −0.40 | |
| −0.60 | −2.30 | |
| −0.60 | −2.30 | |
| token-level KL contribution | 0 | 0 |
| 0.90 | −0.40 |
Initially the KL term is zero since , so the policy gradient pushes probability mass toward -like completions (positive advantage) and away from -like ones (negative advantage). After one PPO update suppose rises to while stays at . Now:
The KL penalty shaves a small amount off the effective reward as the policy drifts from the reference, which slows further movement once the marginal gain from increasing is outweighed by the KL cost — this is exactly the tilted-distribution equilibrium described above, being approached iteratively.
Common pitfalls & traps
| Pitfall | Why it happens | Mitigation |
|---|---|---|
| Reward hacking / over-optimization | Policy exploits reward-model blind spots outside training distribution | KL penalty, reward-model ensembling, early stopping, periodic re-annotation |
| Reward model overfits annotator idiosyncrasies | Small preference datasets, annotator disagreement not modeled | Larger diverse annotator pool, disagreement-aware loss, calibration checks |
| Mode collapse / low-diversity outputs | Policy converges to a narrow high-reward mode, losing output diversity | Entropy bonus, sampling temperature during rollout, diversity-aware evaluation |
| Confusing reward ordering with reward calibration | Bradley-Terry loss only trains relative comparisons, not absolute scale | Never interpret raw reward-model scores as calibrated utility; re-tune per model |
| Distribution shift between SFT and RL rollouts | Policy explores states never seen during reward-model training | On-policy re-sampling and re-labeling of preference data during RLHF iterations |
| Forgetting the KL anchor drifts if is itself updated | Some pipelines mistakenly update the reference policy alongside the trainable one | Keep strictly frozen for the duration of one RL phase |
Pioneers & history
RLHF's mathematical backbone predates deep learning by nearly a century: the Bradley-Terry model for paired comparisons was published in the 1950s for ranking objects from pairwise judgments, itself building on Thurstone's 1920s work on comparative judgment in psychology. The RL formalism that RLHF fine-tunes into came from the reinforcement learning tradition; the marriage of preference-based reward learning with deep policy gradients is a 2010s-2020s development.
Origins · 1 minPaul Christiano and how this was discovered
Paul Christiano led the 2017 work "Deep Reinforcement Learning from Human Preferences" at OpenAI (with Jan Leike and collaborators), which demonstrated that a reward model trained from a modest number of pairwise human comparisons could substitute for hand-coded reward functions in continuous-control and Atari tasks, using policy-gradient methods to optimize against the learned reward. This paper established the exact three-part structure — preference collection, reward-model fitting, RL fine-tuning — later scaled up for language models.
Where this matters
RLHF is the mechanism behind the shift from raw pretrained language models to deployed conversational assistants: the supervised-fine-tuning-plus-preference-optimization recipe (InstructGPT and its successors) is the standard pathway used across major chat-oriented deployments, and reward models built this way are also used as automatic evaluators ("reward-model-as-judge") to filter and rank generated candidates at inference time. Beyond text, the same three-stage recipe applies to code-generation assistants (preferring correct, idiomatic, and safe code), to summarization systems (trading off faithfulness and brevity), and to robotics and simulated agents where a human's qualitative preference between two trajectories substitutes for an unavailable reward function — directly inheriting the reward-inference perspective from Imitation and Inverse Reinforcement Learning. Constitutional and rule-based variants replace or supplement human preference labels with model-generated critiques, but still rely on the same Bradley-Terry reward-modeling and KL-regularized policy-optimization core. Because the RL stage is exactly an instance of Deep Policy Gradient Methods applied to a learned reward, any advance in PPO stability, sample efficiency, or variance reduction propagates directly into better, cheaper RLHF pipelines, which is why the technique remains an active area connecting classical preference statistics, inverse reinforcement learning theory, and large-scale deep RL engineering.
Ask the tutor: How does the choice of the KL-penalty coefficient β interact with reward model miscalibration, and how would you tune it in practice?
Is RLHF a form of inverse reinforcement learning?
Yes, in spirit though not in the classical formulation. Classical inverse reinforcement learning, as covered under Imitation and Inverse Reinforcement Learning, infers a reward function from observed expert trajectories that are assumed near-optimal. RLHF instead infers a reward function from pairwise comparisons between candidate outputs, using the Bradley-Terry statistical model rather than trajectory-matching assumptions. Both approaches share the core idea: reward is not given, it is recovered from behavioral or judgment signal, then used to drive forward reinforcement learning. RLHF can be seen as an IRL variant specialized to comparison-based supervision, which is often more reliable to elicit from humans than absolute reward labels or full demonstrations.
Why not just have humans assign a numeric reward directly instead of pairwise preferences?
Humans are demonstrably inconsistent and poorly calibrated at assigning absolute numeric scores — the same annotator might rate similar outputs very differently depending on mood, anchoring, or scale drift across sessions. Pairwise comparisons are a much easier and more reliable elicitation task: judging "which of these two is better" requires only relative, not absolute, judgment, and this format naturally fits the Bradley-Terry statistical model, which has well-understood convergence properties. Empirically, reward models trained from pairwise comparisons are more stable and require fewer labels to reach a given ranking accuracy than models trained from noisy absolute scores.
What exactly does reward hacking look like in practice?
Reward hacking occurs when the policy discovers outputs that score highly under the learned reward model but are judged poor by actual humans — for instance, generating overly long, repetitive, or sycophantic text because the reward model happens to correlate length or agreeable tone with quality in its training data, even though that correlation does not hold universally. Because the reward model is a finite neural network trained on a limited and possibly biased sample of comparisons, it has systematic blind spots, and an RL optimizer is very good at finding and exploiting those blind spots. The KL penalty, ensembled reward models, and periodic re-collection of preference data on the current policy's outputs are the standard mitigations.
How does Direct Preference Optimization relate to the RLHF pipeline described here?
DPO exploits the closed-form solution to the KL-regularized reward-maximization problem — the optimal policy is a tilted version of the reference policy, proportional to . Substituting this relationship back into the Bradley-Terry preference likelihood yields a loss expressed purely in terms of the policy's own log-probabilities, with no explicit reward model and no PPO rollout loop required. DPO therefore trains the policy directly on preference pairs via a single supervised-style loss, mathematically targeting the same optimum as full RLHF under the same modeling assumptions, at substantially lower engineering and compute cost, though it can be less flexible for sequential or multi-turn reward structures.
Why is the reward model frozen during the RL fine-tuning stage instead of continuing to train it jointly?
Freezing the reward model keeps the optimization target for the policy stationary, which is required for PPO's convergence guarantees and clipped-objective mechanics to behave sensibly — a reward function that changes underneath a policy-gradient method violates the assumptions that make the advantage estimates meaningful across PPO's inner epochs. In production pipelines, the reward model is periodically retrained offline on freshly collected preferences from newer policy rollouts (to combat distribution shift), but within a single RL fine-tuning phase it is held fixed, exactly like a fixed environment reward function in standard RL.
Does RLHF require a reward function that is Markovian or per-step, as in classical RL?
No — in the language-model setting, the reward model typically scores only the complete generated sequence, making the reward sparse and terminal rather than dense per-token, which is a significant deviation from the classical dense-reward assumptions common in Deep Policy Gradient Methods applied to control tasks. This sparsity is one reason PPO with a learned value function (which must bootstrap value estimates across many tokens before any reward signal arrives) can be sample-inefficient in RLHF, and it partly motivates alternatives like DPO that bypass the need to propagate credit through a long autoregressive rollout via a value function at all.
What role does the value function play in the PPO stage of RLHF?
The value function estimates the expected total (KL-adjusted) reward from a given partial sequence, and is used to compute the advantage estimates that reduce variance in the policy gradient — typically via Generalized Advantage Estimation (GAE), exactly as in standard PPO applications described under Deep Policy Gradient Methods. Because the true reward only arrives at the end of the sequence, the value function must implicitly learn to predict, token by token, how promising a partial completion is likely to become, which is a nontrivial credit-assignment problem and one more reason RLHF training can require careful tuning of the value-loss coefficient and learning rate relative to the policy loss.