Reinforcement Learning from Human Feedback

A base language model finishes "The best way to get away with a crime is" as fluently as it finishes any other prompt. This happens because raw next-token prediction has no notion of what humans actually want. Instruction Tuning narrows this gap by showing the model examples of desirable behavior. But it can only teach responses that a human demonstrator actually wrote down. Reinforcement Learning from Human Feedback (RLHF) goes further. It uses The Reward Model as a learned proxy for human preferences. Then it optimizes the language model against that proxy with reinforcement learning. This lets the model discover good responses that no human ever demonstrated. The core difficulty is that "good text" is not a differentiable function of tokens. You cannot backpropagate through "helpful, honest, and harmless." What you can do is train humans to rank outputs. Then you distill those rankings into a scalar reward model. Next, you use policy-gradient reinforcement learning to push a language model toward generating outputs that this reward model scores highly. This is the same move that turned Atari-playing agents from imitators into superhuman players. Replace an unattainable supervised target with a learnable reward signal, and let trial-and-error optimization do the rest. RLHF is the training stage that turned research-grade language models into products like conversational assistants. It is why the same underlying transformer, after RLHF, refuses harmful requests and admits uncertainty. It also follows formatting instructions, and generally "feels" cooperative rather than merely fluent. Every large-scale aligned model deployed at scale has some variant of this pipeline in its history. This includes chat assistants, coding copilots, and summarization tools. These pipelines are typically built on Proximal Policy Optimization (PPO) or a related policy-gradient method. This article gives the full mechanics: the RLHF objective, and the PPO algorithm adapted to token-level generation. It also covers the KL-penalty that keeps the policy from degenerating. It addresses the practical pitfalls too, such as reward hacking, mode collapse, and instability. These pitfalls make this stage notoriously fragile to implement correctly. It closes by connecting RLHF to the broader questions of alignment and safety that motivate it in the first place.

Key takeaways
  • RLHF fine-tunes an instruction-tuned language model using RL, with a learned The Reward Model supplying the training signal instead of ground-truth labels.
  • The policy is the language model itself; actions are token choices; the episode reward comes from scoring the completed response.
  • A KL-divergence penalty against the original (reference) policy keeps the fine-tuned model close to fluent, sane text and prevents reward hacking.
  • Proximal Policy Optimization (PPO) is the standard optimizer: it takes small, clipped policy-gradient steps to avoid destructively large updates.
  • RLHF is data- and compute-heavy, unstable to tune, and vulnerable to reward-model exploitation — this motivates simpler alternatives like DPO, but PPO-based RLHF remains foundational.
  • RLHF is the direct technical ancestor of the broader challenges studied under Alignment & the Alignment Problem and Safety & Red-Teaming.
The core insight

RLHF turns human preference judgments into a scalar reward signal, then uses policy-gradient reinforcement learning (typically PPO with a KL penalty) to steer a language model's entire output distribution toward high-reward, human-preferred behavior.

The idea

Formally, RLHF treats text generation as a sequential decision process. Given a prompt xx, the language model πθ\pi_\theta is a policy: at each step it observes the prompt and tokens generated so far (the state) and samples the next token (the action) from a distribution over the vocabulary. Once the model emits an end-of-sequence token, the full response yy is scored by a fixed, pretrained reward model rϕ(x,y)r_\phi(x, y), itself trained on human preference comparisons (see The Reward Model). This scalar becomes the episode's reward, and reinforcement learning is used to adjust θ\theta so that πθ\pi_\theta places more probability mass on high-reward completions. Two design choices make this different from generic RL. First, the reward is sparse and terminal — it arrives only once, after the whole sequence is generated, not per token, since human judgments of "good response" naturally apply to the full text rather than to individual words. Second, unconstrained reward maximization is dangerous: a policy can find degenerate text that fools the reward model (reward hacking) while being incoherent or repetitive to a human reader. RLHF addresses this by adding a KL-divergence penalty between the trained policy πθ\pi_\theta and a frozen reference policy πref\pi_{\text{ref}} (usually the instruction-tuned model before RL). The per-token reward actually optimized is

rtotal(x,y)=rϕ(x,y)−β DKL ⁣(πθ(⋅∣x,y<t) ∥ πref(⋅∣x,y<t))r_{\text{total}}(x, y) = r_\phi(x, y) - \beta \, D_{KL}\!\big(\pi_\theta(\cdot \mid x, y_{<t}) \,\|\, \pi_{\text{ref}}(\cdot \mid x, y_{<t})\big)

where β\beta controls how tightly the policy is tethered to the reference. This penalty is what keeps RLHF from collapsing into gibberish that exploits reward-model blind spots; it is the load-bearing regularizer of the whole method.

How it works

The RLHF loop has four ingredients, three of which are frozen during RL: a frozen reference policy πref\pi_{\text{ref}} (the instruction-tuned model), a frozen reward model rϕr_\phi, a trainable policy πθ\pi_\theta (initialized from πref\pi_{\text{ref}}), and often a trainable value function VψV_\psi used to reduce variance in the policy-gradient estimate. Training proceeds in repeated rounds: sample prompts, generate responses with the current policy, score them, compute advantages, and take a clipped policy-gradient step. This is Proximal Policy Optimization (PPO) specialized to autoregressive text generation.

Step 1 — Rollout. Sample a batch of prompts x1,…,xBx_1, \dots, x_B from a prompt distribution (often a mixture of instruction-tuning prompts and user-style queries). For each prompt, generate a response yi∼πθ(⋅∣xi)y_i \sim \pi_\theta(\cdot \mid x_i) token by token, recording the log-probability the policy assigned to each chosen token.

Step 2 — Scoring. Pass each completed (xi,yi)(x_i, y_i) through the reward model to get a scalar rϕ(xi,yi)r_\phi(x_i, y_i). Compute the per-token KL penalty between πθ\pi_\theta and πref\pi_{\text{ref}} at every generation step, and subtract β\beta times it from the reward, typically added only at the final token (or distributed across tokens).

Step 3 — Advantage estimation. Use the value function VψV_\psi to estimate, at each token position tt, how much better the actual outcome was than expected. Generalized Advantage Estimation (GAE) computes

At=∑k=0T−t−1(γλ)k δt+k,δt=rt+γVψ(st+1)−Vψ(st)A_t = \sum_{k=0}^{T-t-1} (\gamma\lambda)^k \, \delta_{t+k}, \qquad \delta_t = r_t + \gamma V_\psi(s_{t+1}) - V_\psi(s_t)

where γ\gamma is a discount factor (often close to 1) and λ\lambda trades off bias and variance.

Step 4 — PPO update. Update θ\theta by maximizing the clipped surrogate objective, and update ψ\psi by regressing VψV_\psi toward observed returns. Clipping is what makes PPO "proximal": it prevents any single update from moving the policy so far that the advantage estimates (computed under the old policy) become invalid. ```

# RLHF training loop with PPO, applied to token-level generation Input: pi_theta : trainable policy, initialized from pi_ref pi_ref : frozen reference policy (instruction-tuned model) r_phi : frozen reward model V_psi : trainable value function prompts : distribution of prompts x beta : KL penalty coefficient epsilon : PPO clip range K : number of PPO epochs per batch of rollouts for iteration = 1, 2, ... do

# --- Step 1: Rollout --- batch = [] for i = 1 to B: x = sample(prompts) y, logp_old = generate(pi_theta, x) # token-by-token sampling batch.append((x, y, logp_old))

# --- Step 2: Scoring with KL penalty --- for (x, y, logp_old) in batch: reward_terminal = r_phi(x, y) for t = 1 to len(y): kl_t = logp_old[t] - logprob(pi_ref, x, y[:t]) r[t] = -beta * kl_t # per-token penalty r[len(y)] += reward_terminal # reward only at end

# --- Step 3: Advantage estimation (GAE) --- for (x, y, r) in batch: V = [V_psi(x, y[:t]) for t in 1..len(y)+1] delta[t] = r[t] + gamma V[t+1] - V[t] A[t] = sum_{k>=0} (gamma lambda)^k * delta[t+k] R[t] = A[t] + V[t] # target return for value fn

# --- Step 4: PPO clipped update --- for epoch = 1 to K: for (x, y, logp_old, A, R) in batch: logp_new = logprob(pi_theta, x, y) ratio = exp(logp_new - logp_old) # importance ratio per token unclipped = ratio A clipped = clip(ratio, 1 - epsilon, 1 + epsilon) A L_policy = -mean(min(unclipped, clipped)) L_value = mean((V_psi(x, y) - R)^2) L_entropy = -mean(entropy(pi_theta(x, y))) # optional bonus loss = L_policy + c1 L_value - c2 L_entropy update(theta, psi) via gradient descent on loss return pi_theta ``` The clipping term is the algorithmic heart of PPO. If the importance ratio ρt=πθ(at∣st)/πθold(at∣st)\rho_t = \pi_\theta(a_t\mid s_t) / \pi_{\theta_{\text{old}}}(a_t\mid s_t) moves far from 1 in a direction that would increase the surrogate loss, clipping caps its contribution, so the optimizer cannot be rewarded for straying arbitrarily far from the policy that generated the data. This is what allows multiple gradient epochs (K>1K > 1) over the same rollout batch without the update becoming an invalid extrapolation.

Figure
The RLHF pipeline: from reward model to updated policy
Prompt x Policy π_θ (trainable LM) Reference π_ref (frozen, instruction-tuned) Response y Reward model r_φ (frozen) Value fn V_ψ (trainable) KL(π_θ ‖ π_ref) penalty, weight β total reward = r_φ − β·KL PPO clipped update advantage A_t via GAE clip(ratio, 1±ε)·A_t update θ (loop back to policy)

Complexity & correctness

Time and space complexity. Each PPO iteration requires: (1) a full autoregressive rollout from πθ\pi_\theta, costing O(B⋅T⋅L)O(B \cdot T \cdot L) where BB is batch size, TT is response length, and LL is the per-token forward-pass cost (roughly linear in model parameter count for a transformer decoding step, ignoring KV-cache reuse which makes decoding itself O(T)O(T) sequential steps each O(1)O(1) amortized model calls); (2) one reward-model forward pass per response, O(B⋅T⋅Lr)O(B \cdot T \cdot L_r); (3) KK epochs of gradient updates over the batch, each requiring a forward and backward pass through πθ\pi_\theta and VψV_\psi, costing O(K⋅B⋅T⋅L)O(K \cdot B \cdot T \cdot L). In practice, four full model copies must reside in memory or be swapped: the policy, the reference policy, the reward model, and the value function (often the value function shares weights with the policy via a separate head, reducing this to three). This is why RLHF is markedly more expensive than supervised instruction tuning — it multiplies the cost of standard fine-tuning by the rollout generation cost and the number of concurrently loaded models.

Why the algorithm is correct (policy-gradient argument). The RL objective is to maximize expected total reward,

J(θ)=Ex∼prompts, y∼πθ(⋅∣x)[rtotal(x,y)].J(\theta) = \mathbb{E}_{x \sim \text{prompts},\, y \sim \pi_\theta(\cdot \mid x)}\big[ r_{\text{total}}(x,y) \big].

The policy-gradient theorem gives

∇θJ(θ)=E[∑t∇θlog⁡πθ(at∣st)⋅At],\nabla_\theta J(\theta) = \mathbb{E}\Big[\sum_t \nabla_\theta \log \pi_\theta(a_t \mid s_t) \cdot A_t\Big],

which is unbiased regardless of how AtA_t is estimated, provided AtA_t does not depend on ata_t in a way that reintroduces bias (a standard baseline-subtraction argument: subtracting any function of the state alone from the reward does not change the expected gradient, because Eat[∇θlog⁡πθ(at∣st)]=0\mathbb{E}_{a_t}[\nabla_\theta \log \pi_\theta(a_t\mid s_t)] = 0). This is why using the value function Vψ(st)V_\psi(s_t) as a baseline reduces variance without introducing bias, and why GAE — an exponentially weighted average of kk-step advantage estimates — trades a controllable amount of bias for a large variance reduction, governed by λ\lambda. PPO's clipped surrogate is a correctness-preserving approximation to Trust Region Policy Optimization (TRPO): TRPO proves that maximizing a surrogate objective subject to a KL constraint on policy change guarantees monotonic improvement in expected reward, up to a bound involving the maximum KL divergence between old and new policy. PPO replaces the hard constraint with a soft clipping penalty that empirically achieves similar stability at much lower computational cost (no second-order trust-region computation), at the price of losing TRPO's formal monotonic-improvement guarantee — PPO's correctness is thus empirical and heuristic rather than proven, which is an honest caveat of the method.

Why the KL penalty matters for correctness of the overall objective, not just stability. The reward model rϕr_\phi is only accurate in the region of output space it was trained on — human preference labels were collected on responses from earlier policies (SFT / earlier RLHF checkpoints), not on arbitrary token sequences. Outside this region, rϕr_\phi can be arbitrarily wrong (this is the mechanism behind reward hacking: policy gradient will happily climb toward inputs that trick a fixed scoring function, exactly as adversarial examples exploit fixed classifiers). The KL penalty keeps πθ\pi_\theta's output distribution within a neighborhood of πref\pi_{\text{ref}}'s distribution, which is by construction the distribution the reward model was calibrated on, so the reward signal remains trustworthy in expectation. This is a distributional-shift argument, not merely a fluency heuristic.

Tradeoffs. Larger β\beta gives a safer, more conservative policy that stays close to instruction-tuned behavior but captures less of the reward model's signal; smaller β\beta extracts more preference-aligned behavior but risks reward hacking and degenerate text. Choosing β\beta, the clip range ϵ\epsilon, GAE's λ\lambda, and learning rates is empirically delicate — PPO-based RLHF is notorious for being sensitive to these hyperparameters, and small implementation bugs (wrong reward normalization, KL computed against the wrong reference distribution, value-function collapse) silently degrade quality without crashing training.

Worked example

Consider a toy instruction-tuned policy answering the prompt: "Write one sentence recommending a good first programming language." Suppose the reward model has learned to prefer concise, concrete, non-hedging answers (higher reward for specificity, lower for filler).

RolloutSampled response yyrϕ(x,y)r_\phi(x,y)KL to πref\pi_{\text{ref}} (avg/token)Total reward (β=0.1\beta=0.1)
1"Python is a great first language because it has simple syntax and huge community support."0.820.050.815
2"It really depends on your goals, there are many good options, you should consider several factors."0.310.020.308
3"Python Python Python Python is is is great great great."0.95 (reward hacked)3.400.61
4"Python."0.400.010.399

Rollout 3 illustrates reward hacking directly: some degenerate repetition happens to score very high under an imperfectly generalizing reward model, perhaps because the training data for rϕr_\phi under-represented such repetitive strings. Without the KL penalty, PPO's gradient would push hard toward more text like Rollout 3, since it has the single highest raw reward (0.95). With the KL penalty active, the enormous divergence from πref\pi_{\text{ref}} (which would never produce such repetition) incurs a penalty of 0.1×3.40=0.340.1 \times 3.40 = 0.34, dropping the total reward for Rollout 3 below Rollout 1's. The advantage estimates computed from these totals therefore favor Rollout 1, and the clipped PPO update nudges πθ\pi_\theta's probability mass toward concise, concrete answers like Rollout 1 while pulling it away from both hedging (Rollout 2) and degenerate repetition (Rollout 3). Over many iterations and prompts, this shifts the policy's overall output distribution toward the region of response-space that both scores well under rϕr_\phi and stays plausible under πref\pi_{\text{ref}} — exactly the intended behavior.

Common pitfalls & traps

PitfallWhy it happensConsequence
Reward hackingReward model has blind spots outside its training distributionPolicy finds degenerate high-reward text (repetition, sycophancy, verbosity inflation)
KL coefficient too smallβ\beta tuned only for reward maximization, not distributional safetyPolicy drifts far from reference, output quality collapses despite rising reward-model score
KL coefficient too largeOverly cautious tuningPolicy barely changes from instruction-tuned baseline; RLHF gains are negligible
Value function undertrainedInsufficient updates or too high a learning rate causing instabilityHigh-variance advantage estimates, noisy or divergent policy updates
Reward not normalized/whitenedRaw reward-model scores have unstable scale across checkpointsLearning rate effectively varies per batch, causing instability
Stale importance ratiosToo many PPO epochs KK per rollout batch without re-samplingRatio ρt\rho_t drifts far from 1, clipping saturates, gradient signal vanishes
Length bias in reward modelReward model correlates length with quality from biased preference dataPolicy inflates response length without improving actual quality

Pioneers & history

Origins · 1 minJohn Schulman and how this was discovered
JS
John Schulman
1986–present · Co-developer of Trust Region Policy Optimization and Proximal Policy Optimization, and a lead architect of RLHF pipelines used to train instruction-following language models

Schulman's doctoral and postdoctoral work on trust-region and clipped surrogate objectives at UC Berkeley and OpenAI supplied the exact optimizer that made RLHF computationally practical at language-model scale, turning a theoretically elegant but expensive trust-region method into an engineering-tractable clipped-objective algorithm.

History
2017
— Trust Region Policy Optimization and Proximal Policy Optimization published, establishing stable policy-gradient methods for high-dimensional continuous and discrete control.
2017
— "Deep reinforcement learning from human preferences" demonstrates that a reward model trained on pairwise human comparisons can substitute for a hand-coded reward function in RL.
2019–2020
— Human preference fine-tuning applied to text summarization and language modeling, showing PPO against a learned reward model improves human-judged quality over supervised baselines alone.
2022
— InstructGPT combines instruction tuning with RLHF via PPO, establishing the now-standard three-stage pipeline: pretraining, supervised fine-tuning, reward-model-driven RL.
2022–2023
— RLHF deployed at scale in conversational assistants, becoming a standard industrial pipeline stage alongside ongoing work on cheaper alternatives such as Direct Preference Optimization.

Where this matters

RLHF is the training stage most directly responsible for making large language models behave like cooperative assistants rather than raw text predictors. Production conversational systems use RLHF (or closely related preference-optimization methods) to shape refusal behavior on harmful requests, calibrate hedging and uncertainty expression, enforce formatting and instruction-following fidelity, and reduce toxic or biased outputs relative to the pretraining distribution. Code-generation assistants use analogous pipelines with reward signals derived from unit-test pass rates or human coding-quality judgments. Because the entire method rests on optimizing against a proxy that only approximates true human intent, RLHF is the direct technical entry point into the broader questions studied under Alignment & the Alignment Problem — including specification gaming, goal misgeneralization, and the difficulty of scaling human oversight — and into the practical discipline of Safety & Red-Teaming, which stress-tests RLHF-trained models for exactly the reward-hacking and distributional-shift failures this article's optimization argument predicts.

Ask the tutor: How would the RLHF objective and update rule change if the reward model produced per-token rewards instead of a single terminal score?

Why not just use supervised fine-tuning on the best human-written responses, skipping RL entirely?

Supervised fine-tuning, including Instruction Tuning, can only teach the model to imitate responses a human actually wrote. It has no mechanism for the model to discover a response that scores even higher than any human demonstration, and it cannot express graded preferences ("response A is somewhat better than B") — only exact targets. RLHF instead uses a reward model trained on comparative human judgments, letting the policy explore its own output space and receive a scalar signal on any response it generates, including ones no human wrote. This lets the model be optimized directly against what humans prefer, rather than against what humans happened to demonstrate, which empirically produces better-calibrated and more helpful behavior than supervised fine-tuning alone.

What exactly is the "reward model" being optimized against, and why can it be wrong?

The reward model, covered in The Reward Model, is a neural network trained to predict human pairwise preference judgments, typically by fitting a Bradley-Terry style model to comparisons collected from human raters. It is accurate only in the regions of output space represented in its training comparisons. Because RLHF's policy actively searches for high-scoring outputs, it can drift into regions the reward model never saw during training, where its scores no longer track true human preference. This is the root cause of reward hacking, and it is why the KL penalty against a reference policy is essential rather than optional.

Why is PPO used instead of simpler policy-gradient methods like REINFORCE?

Plain REINFORCE has extremely high-variance gradient estimates and no mechanism to prevent destructively large updates, which is especially dangerous with a huge, expensive-to-sample policy like a language model. PPO reduces variance via a learned value-function baseline and generalized advantage estimation, and prevents catastrophic updates via the clipped surrogate objective, which caps how much the policy can change per update relative to the data it was estimated from. This lets practitioners reuse a batch of rollouts for several gradient-descent epochs safely, substantially improving sample efficiency, since generating rollouts (running the language model forward) is the most expensive part of the loop.

Does the value function need to be a separate model, or can it share the policy's weights?

Either design is used in practice. Sharing weights (the transformer body is shared, with the value function reading from an added linear head) saves memory and compute, since decoding activations are reused, but risks interference between the policy's language-modeling objective and the value function's regression objective. A fully separate value network avoids this interference at the cost of essentially doubling memory for that component. Both choices are valid engineering tradeoffs; the correctness argument for PPO does not depend on which one is used, only that the value function accurately estimates expected future reward under the current policy.

What happens if the KL penalty coefficient β is set to zero?

With β = 0, the policy is optimized purely to maximize the reward model's score, with no tether to the reference policy's distribution. Early in training this can look like rapid improvement, since reward scores climb quickly. Empirically, this reliably leads to reward hacking: the policy discovers idiosyncratic patterns the reward model over-scores, producing text that is fluent-looking to the reward model but degenerate or repetitive to human readers. This failure mode directly demonstrates why the KL penalty is a correctness-preserving component of the objective, not merely a stability trick.

How does RLHF relate to Direct Preference Optimization (DPO) and other newer methods?

DPO and related methods reformulate the RLHF objective so that the optimal policy under the KL-regularized reward-maximization problem can be derived in closed form from preference data directly, without training an explicit reward model or running an RL loop at all. This removes the instability and hyperparameter sensitivity of PPO-based RLHF, at the cost of losing the flexibility to use reward models trained on data distributions different from the fine-tuning prompts, or to incorporate reward signals from sources other than pairwise comparisons (like automated verifiers). RLHF with PPO remains the more general and, in many production settings, still the more capable framework, especially where reward signals are complex or multi-source.

Is RLHF the same thing as "alignment"?

No — RLHF is one specific technique used to pursue alignment, not alignment itself. It addresses a narrow engineering problem: how to optimize a language model against a learned proxy for human preference using reinforcement learning. The broader challenge, covered under Alignment & the Alignment Problem, includes questions RLHF does not solve on its own, such as whether the reward model itself captures true human values, how behavior generalizes to situations unlike any in the training data, and how to detect deceptive or manipulated reward signals, which is the domain of Safety & Red-Teaming.

Before this

Where this leads