Skip to content
E
Educatum

Explain the concept of Reinforcement Learning from Human Feedback (RLHF) and its application in fine-tuning language models.

Curated by Educatum AI teamLast updated:
Large Language Models (LLMs)
Direct Answer

Reinforcement Learning from Human Feedback (RLHF) aligns language models with human preferences via a three-stage pipeline: supervised fine-tuning (SFT), training a Bradley-Terry reward model on pairwise comparisons, and optimizing the policy using PPO with a KL penalty against the reference model. Because sampling discrete tokens is non-differentiable, RL policy gradients adjust token probabilities based on expected reward while the KL term curbs reward hacking. Modern pipelines also adopt simpler alternatives like Direct Preference Optimization (DPO) and GRPO.

Study Card: Reinforcement Learning from Human Feedback (RLHF)

Direct Answer

Reinforcement Learning from Human Feedback (RLHF) (Christiano et al., 2017; Ouyang et al., 2022) aligns pre-trained language models with nuanced human preferences (helpfulness, honesty, safety, formatting) through a three-stage pipeline:

  1. Supervised Fine-Tuning (SFT): Fine-tune the base LLM on curated instruction-response demonstrations to obtain an initial reference policy πref\pi_{\text{ref}}.
  2. Reward Model (RM) Training: Collect pairwise human comparisons (x,yw,yl)(x, y_w, y_l) where completion ywy_w is preferred over yly_l, and train scalar reward model rϕ(x,y)r_\phi(x, y) using the Bradley-Terry cross-entropy loss:

LRM(ϕ)=−E(x,yw,yl)[log⁡σ(rϕ(x,yw)−rϕ(x,yl))]\mathcal{L}_{\text{RM}}(\phi) = -\mathbb{E}_{(x, y_w, y_l)}\left[\log \sigma\big(r_\phi(x, y_w) - r_\phi(x, y_l)\big)\right]

  1. RL Policy Optimization (e.g., PPO): Sample discrete completions y∼πθ(⋅∣x)y \sim \pi_\theta(\cdot \mid x) and update πθ\pi_\theta using policy gradients (since discrete sampling is non-differentiable) to maximize reward while penalizing KL divergence from the frozen SFT model πref\pi_{\text{ref}}:

max⁡θEx∼D, y∼πθ(⋅∣x)[rϕ(x,y)−β DKL(πθ(y∣x) ∥ πref(y∣x))]\max_\theta \mathbb{E}_{x \sim \mathcal{D},\, y \sim \pi_\theta(\cdot \mid x)}\left[r_\phi(x, y) - \beta\, D_{\text{KL}}\big(\pi_\theta(y \mid x) \,\|\, \pi_{\text{ref}}(y \mid x)\big)\right]

The KL penalty −βDKL-\beta D_{\text{KL}} is critical: without it, the policy exploits imperfections in the learned reward model (reward hacking / Goodhart’s law), outputting gibberish or overly verbose boilerplate that scores high under rϕr_\phi while degrading real quality.

Key Terms

  • Supervised Fine-Tuning (SFT): Initial instruction adaptation producing the baseline policy πref\pi_{\text{ref}}.
  • Bradley-Terry Reward Model: Predicts scalar preference scores rϕ(x,y)r_\phi(x, y) trained from pairwise human rankings (yw≻yl)(y_w \succ y_l).
  • PPO (Proximal Policy Optimization): Clipped policy-gradient algorithm stabilizing LLM updates alongside a value critic and per-token KL penalty.
  • KL Divergence Penalty (βDKL\beta D_{\text{KL}}): Anchors the RL policy near πref\pi_{\text{ref}} to preserve fluency and prevent reward hacking.
  • DPO & GRPO: Modern alignment alternatives—DPO derives an exact closed-form preference loss without an explicit RM or RL loop, while GRPO uses group-relative normalized rewards to drop the PPO value critic.

Example

Consider aligning a coding assistant:

  • An SFT model may generate syntactically valid code yet refuse needlessly, ignore edge cases, or miss concise formatting.
  • Annotators compare pairs of candidate answers (yw,yl)(y_w, y_l), teaching the reward model to prefer clean, accurate solutions with clear explanations.
  • During PPO, the policy samples candidate completions, receives advantages from the reward model minus a token-level KL penalty βlog⁡πθ(yt∣x,y<t)πref(yt∣x,y<t)\beta \log \frac{\pi_\theta(y_t \mid x, y_{<t})}{\pi_{\text{ref}}(y_t \mid x, y_{<t})}, and increases probability on preferred reasoning patterns without drifting into repetitive reward-hacking phrases.

Code Implementation

import copy
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.distributions import Categorical


def bradley_terry_rm_loss(reward_chosen, reward_rejected):
    """Stage 2 loss: trains Reward Model r_phi(x, y) on pairwise preference data."""
    return -F.logsigmoid(reward_chosen - reward_rejected).mean()


class ToyPolicyLM(nn.Module):
    def __init__(self, state_dim=16, vocab_size=10):
        super().__init__()
        self.net = nn.Linear(state_dim, vocab_size)

    def forward(self, prompt_emb):
        return self.net(prompt_emb)  # Token logits


torch.manual_seed(42)
state_dim, vocab_size, batch_size = 16, 10, 32

# Stage 2 demonstration: Bradley-Terry loss on chosen vs. rejected scalar rewards
r_w = torch.tensor([2.1, 1.4, 0.8])
r_l = torch.tensor([0.5, -0.3, 0.9])
print(f"Bradley-Terry RM loss: {bradley_terry_rm_loss(r_w, r_l).item():.4f}")

# Stage 3 demonstration: Discrete token sampling + policy gradient + KL penalty vs. frozen SFT ref
policy = ToyPolicyLM(state_dim=state_dim, vocab_size=vocab_size)
ref_policy = copy.deepcopy(policy).eval()
for p in ref_policy.parameters():
    p.requires_grad_(False)

# Synthetic reward table assigning higher reward to target token IDs >= 7
token_rewards = torch.linspace(-1.0, 2.0, vocab_size)
optimizer = optim.AdamW(policy.parameters(), lr=5e-2)
kl_beta = 0.05

for step in range(1, 21):
    prompts = torch.randn(batch_size, state_dim)
    logits = policy(prompts)
    dist = Categorical(logits=logits)

    # Discrete token sampling (non-differentiable -> requires score-function / PPO gradient)
    sampled_tokens = dist.sample()
    log_probs = dist.log_prob(sampled_tokens)

    with torch.no_grad():
        ref_dist = Categorical(logits=ref_policy(prompts))
        ref_log_probs = ref_dist.log_prob(sampled_tokens)
        raw_reward = token_rewards[sampled_tokens]
        # Per-sample KL penalty estimate: log pi_theta(a|s) - log pi_ref(a|s)
        kl_penalty = log_probs.detach() - ref_log_probs
        total_reward = raw_reward - kl_beta * kl_penalty
        # Mean baseline reduces policy-gradient variance
        advantages = total_reward - total_reward.mean()

    pg_loss = -(log_probs * advantages).mean()
    optimizer.zero_grad()
    pg_loss.backward()
    optimizer.step()

    if step in (1, 10, 20):
        print(
            f"Step {step:2d} | Mean raw reward: {raw_reward.mean().item():.4f} | "
            f"Mean KL: {kl_penalty.mean().item():.4f}"
        )
  • Direct Preference Optimization (DPO): Reparameterizes the KL-constrained RLHF objective into a direct supervised cross-entropy loss over (yw,yl)(y_w, y_l) without a separate reward model or online sampling.
  • GRPO (Group Relative Policy Optimization): Replaces the PPO value network with group-normalized rewards over multiple sampled completions per prompt (widely used in reasoning RL).
  • Reward Hacking & Sycophancy: Failure modes where policies game proxy reward models (e.g., agreeing with false user premises or padding length).
  • Constitutional AI (RLAIF): Replaces part of human preference labeling with AI feedback guided by explicit principles.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.