RLHF: Reinforcement Learning from Human Feedback

Reinforcement Learning from Human Feedback (RLHF) is a training paradigm that fine-tunes language models using a reward signal derived from human preference judgments rather than hand-crafted loss functions. It matters because it bridges the gap between what a model can do (capability) and what humans actually want it to do (alignment), and is the primary technique behind the behavioral transformation of base pretrained models into useful assistants like ChatGPT and Claude. The counterintuitive fact: RLHF does not teach the model new knowledge — the model already "knows" how to be helpful after pretraining; RLHF is better understood as a filter that reshapes the probability distribution over outputs to favor responses humans prefer.

The core insight

A pretrained language model has learned to predict text distributions from the internet, which includes unhelpful, harmful, and contradictory content — the model is a mirror of the data, not an assistant. RLHF introduces a learned reward model trained on human preference comparisons (which of two responses is better?), then uses that reward signal to fine-tune the policy via PPO, nudging the model's output distribution toward higher-reward responses. The "aha moment" is recognizing that you are solving an optimization problem over a human utility function that you cannot write down explicitly — you only have noisy pairwise samples from it. This is why RLHF is more similar to learning a surrogate objective than to traditional supervised fine-tuning.

How It Works

RLHF proceeds in three sequential stages: supervised fine-tuning (SFT) to create a well-behaved starting policy, reward model (RM) training on human preference data, and RL fine-tuning of the policy against the RM. Each stage builds on the last, and each has its own loss function and optimization dynamics.

Stage 1: Supervised Fine-Tuning

Starting from a pretrained base model πbase\pi_\text{base}, we collect a dataset of (prompt, high-quality response) pairs — typically written or curated by human contractors — and fine-tune with standard cross-entropy:

1
LSFT(θ)=−E(x,y)∼DSFT[∑t=1∣y∣log⁡πθ(yt∣x,y<t)]\quad \mathcal{L}_\text{SFT}(\theta) = -\mathbb{E}_{(x, y) \sim \mathcal{D}_\text{SFT}}\left[\sum_{t=1}^{|y|} \log \pi_\theta(y_t \mid x, y_{<t})\right]

Explanation: This is the standard next-token prediction loss applied only to the response tokens yy, conditioning on prompt xx, pushing the model to imitate demonstrated behavior.

Symbols:

  • θ\theta: policy (LLM) parameters
  • xx: input prompt
  • yy: target response tokens, yty_t is the tt-th token
  • DSFT\mathcal{D}_\text{SFT}: supervised fine-tuning dataset of curated (prompt, response) pairs

This produces a policy πSFT\pi_\text{SFT} that is better-behaved than the base model and serves as the initialization for both the reward model and the RL stage.

Stage 2: Reward Model Training

Human raters are shown a prompt xx and two candidate completions (yw,yl)(y_w, y_l) — one preferred ("winner") and one not ("loser") — and select which is better. The reward model rϕr_\phi is trained to assign higher scalar scores to preferred completions using the Bradley-Terry preference model:

2
LRM(ϕ)=−E(x, yw, yl)∼Dpref[log⁡σ ⁣(rϕ(x,yw)−rϕ(x,yl))]\quad \mathcal{L}_\text{RM}(\phi) = -\mathbb{E}_{(x,\, y_w,\, y_l)\sim \mathcal{D}_\text{pref}}\left[\log \sigma\!\left(r_\phi(x, y_w) - r_\phi(x, y_l)\right)\right]

Explanation: This is a binary cross-entropy loss that encourages the reward model to assign a higher score to the preferred response ywy_w than the dispreferred response yly_l, modeled as a logistic probability over the score difference.

Symbols:

  • ϕ\phi: reward model parameters
  • rϕ(x,y)∈Rr_\phi(x, y) \in \mathbb{R}: scalar reward assigned to response yy given prompt xx
  • σ(⋅)\sigma(\cdot): sigmoid function
  • ywy_w: human-preferred ("winning") response
  • yly_l: human-dispreferred ("losing") response
  • Dpref\mathcal{D}_\text{pref}: dataset of human preference comparisons

In practice, the reward model is initialized from πSFT\pi_\text{SFT} with the final language model head replaced by a linear layer outputting a single scalar. This weight initialization means the RM starts with strong language understanding.

Stage 3: RL Fine-Tuning with PPO

The policy πθ\pi_\theta is now fine-tuned to maximize the expected reward from rϕr_\phi, subject to a KL-divergence penalty that prevents the policy from drifting too far from πSFT\pi_\text{SFT} (which would cause reward hacking — producing outputs the RM scores highly but humans would not):

3
JRLHF(θ)=Ex∼D, y∼πθ(⋅∣x) ⁣[rϕ(x,y)−β⋅DKL ⁣(πθ(⋅∣x) ∥ πSFT(⋅∣x))]\quad \mathcal{J}_\text{RLHF}(\theta) = \mathbb{E}_{x \sim \mathcal{D},\, y \sim \pi_\theta(\cdot\mid x)}\!\left[r_\phi(x, y) - \beta \cdot D_\text{KL}\!\left(\pi_\theta(\cdot\mid x)\,\|\,\pi_\text{SFT}(\cdot\mid x)\right)\right]

Explanation: The policy is rewarded for producing high-scoring responses according to rϕr_\phi, but penalized for diverging from the SFT policy — the β\beta coefficient controls this alignment-capability trade-off.

Symbols:

  • JRLHF\mathcal{J}_\text{RLHF}: the RL objective to maximize
  • rϕ(x,y)r_\phi(x, y): scalar reward from the frozen reward model
  • β>0\beta > 0: KL penalty coefficient (typically 0.01–0.1)
  • DKL(πθ∥πSFT)D_\text{KL}(\pi_\theta \| \pi_\text{SFT}): per-token KL divergence between the updated policy and the SFT reference
  • D\mathcal{D}: prompt distribution (often separate from SFT/pref data)

The KL term can be decomposed per token, making it compatible with autoregressive generation. The full per-token reward used in PPO is:

4
r^t={rϕ(x,y)−βlog⁡πθ(yt∣x,y<t)πSFT(yt∣x,y<t)t=T−βlog⁡πθ(yt∣x,y<t)πSFT(yt∣x,y<t)t<T\quad \hat{r}_t = \begin{cases} r_\phi(x, y) - \beta \log\frac{\pi_\theta(y_t \mid x, y_{<t})}{\pi_\text{SFT}(y_t \mid x, y_{<t})} & t = T \\ -\beta \log\frac{\pi_\theta(y_t \mid x, y_{<t})}{\pi_\text{SFT}(y_t \mid x, y_{<t})} & t < T \end{cases}

Explanation: The terminal reward from the reward model is applied only at the last token TT, while the KL penalty against the reference policy is applied at every token — this is the standard "reward shaping" used in InstructGPT and subsequent systems. The PPO clipped surrogate objective is then applied to update θ\theta:

5
LPPO(θ)=Et ⁣[min⁡ ⁣(ρt(θ) A^t,  clip ⁣(ρt(θ),1−ϵ,1+ϵ)A^t)]\quad \mathcal{L}_\text{PPO}(\theta) = \mathbb{E}_t\!\left[\min\!\left(\rho_t(\theta)\,\hat{A}_t,\;\text{clip}\!\left(\rho_t(\theta), 1-\epsilon, 1+\epsilon\right)\hat{A}_t\right)\right]

Explanation: PPO clips the probability ratio ρt=πθ/πold\rho_t = \pi_\theta / \pi_\text{old} so that policy updates are not too large in a single step, where A^t\hat{A}_t is the estimated advantage (how much better this action was than the baseline value function predicted).

Symbols:

  • ρt(θ)=πθ(yt∣x,y<t)/πθold(yt∣x,y<t)\rho_t(\theta) = \pi_\theta(y_t \mid x, y_{<t}) / \pi_{\theta_\text{old}}(y_t \mid x, y_{<t}): probability ratio (importance weight)
  • A^t\hat{A}_t: advantage estimate from a learned value function (critic), typically computed via GAE
  • ϵ\epsilon: PPO clip parameter (typically 0.1–0.2)

```python import torch import torch.nn.functional as F def reward_model_loss( r_preferred: torch.Tensor, # shape: (B,) r_rejected: torch.Tensor, # shape: (B,) ) -> torch.Tensor: """Bradley-Terry preference loss for reward model training.""" return -F.logsigmoid(r_preferred - r_rejected).mean()

def kl_penalty_per_token( log_probs_policy: torch.Tensor, # (B, T) log_probs_ref: torch.Tensor, # (B, T) beta: float = 0.05, ) -> torch.Tensor: """Per-token KL penalty: beta (log π_θ - log π_SFT).""" return beta (log_probs_policy - log_probs_ref)

def compute_rlhf_rewards( scalar_reward: torch.Tensor, # (B,) — from reward model, at EOS log_probs_policy: torch.Tensor, # (B, T) log_probs_ref: torch.Tensor, # (B, T) beta: float = 0.05, ) -> torch.Tensor: """Combine terminal reward with per-token KL penalties.""" B, T = log_probs_policy.shape rewards = -kl_penalty_per_token(log_probs_policy, log_probs_ref, beta)

# Add scalar reward at the final token position rewards[:, -1] += scalar_reward return rewards # (B, T) — feed into PPO as token-level rewards ```

researcher · Paul Christiano | b. 1990 | Foundational RLHF Framework

Paul Christiano developed the foundational RLHF framework at OpenAI, specifically the 2017 paper "Deep Reinforcement Learning from Human Preferences" which demonstrated that RL agents could learn complex behaviors from only ~900 human preference queries rather than hand-crafted reward functions. His work directly inspired the InstructGPT line of research and the modern RLHF pipeline used in ChatGPT. Christiano later founded the Alignment Research Center (ARC) and is known for the philosophical concept of "eliciting latent knowledge" (ELK) — the problem of getting models to reveal what they "know" even when they might strategically conceal it.

researcher · John Schulman | b. 1989 | PPO and InstructGPT

John Schulman, an OpenAI researcher who completed his PhD under Pieter Abbeel at UC Berkeley, invented Proximal Policy Optimization (PPO) in 2017 — the specific RL algorithm that became the workhorse of RLHF fine-tuning due to its stability and sample efficiency compared to TRPO. He was the lead author on the InstructGPT paper (2022), which was the first large-scale demonstration that RLHF reliably makes GPT-class models more helpful, harmless, and honest. Schulman is also known for co-developing the REINFORCE algorithm extensions and for his influential lecture notes on deep RL, which have taught the topic to a generation of ML engineers.

Figure
RLHF Three-Stage Pipeline
STAGE 1 STAGE 2 STAGE 3 Supervised FT Pretrained LLM π_base Human Demos (prompt, response) pairs SFT Policy π_SFT Reward Model Training Prompt x + 2 completions Human Rater y_w ≻ y_l Pref Dataset D_pref Reward Model r_φ Bradley-Terry Loss Scalar Reward r ∈ ℝ PPO Fine-Tuning Policy π_θ (init=π_SFT) + KL ref: π_SFT PPO Update max E[r_φ − β·KL] Aligned Policy π_RLHF (helpful, harmless) Data flow: Pretrained LLM → SFT → Reward Model → PPO Aligned Policy
Figure
Reward Model Architecture
Reward Model — Preference Comparison Preferred Response y_w Rejected Response y_l Prompt x (shared context) Transformer LM (shared weights) → hidden state h_w Transformer LM (shared weights) → hidden state h_l ⇔ weight sharing Linear → r_w scalar ∈ ℝ Linear → r_l scalar ∈ ℝ Loss = −log σ(r_w − r_l)

Intuition

The Mental Model

Imagine you are training a new employee at a customer service desk, but you cannot write down every rule for how to respond to every customer — the space of possible interactions is too vast. Instead, you hire a manager who has seen thousands of customer interactions and has strong intuitions about what "good service" looks like. Here is the RLHF analogy:

The employee = the language model policy. It already knows language and has general knowledge, but it doesn't know your specific definition of "good."

The manager = the reward model. You train the manager not by asking them to write ideal responses, but by showing them pairs of responses and asking "which is better?" This is much easier for humans — comparative judgment is more reliable and consistent than absolute judgment (it's easier to say "A is better than B" than to score A on a 1-10 scale). The manager builds up an internal scorecard over thousands of comparisons.

The training loop = the new employee practicing while the manager grades them. The employee generates responses, the manager scores them, and the employee gradually learns to do things the manager rewards. The employee is not memorizing the manager's past feedback — they are internalizing the underlying preference structure. The KL penalty is like telling the employee: "Don't change your personality completely just to please the manager — stay broadly the same person, just better." Without this constraint, the employee might discover one specific phrase the manager always rates highly and just repeat it for every customer (reward hacking). The key insight about why comparison beats demonstration: it is much harder to generate a perfect response from scratch than to identify which of two imperfect responses is better. RLHF exploits this asymmetry — human judgment is cheap and reliable in the comparative mode, even when direct human generation is expensive