Skip to main contentSkip to navigation
ThisIsHowItWorks.in

Complex systems, clearly explained.

An independent visual publication explaining the invisible protocols, networks, infrastructure, and mechanisms that run our world.

Explainers

  • How UPI Works
  • Offline UPI Mechanisms
  • All Explainers (Archive)
  • Topics & Roadmap
  • Curated Library

Publication

  • About Publication
  • Editorial Principles
  • Theme Index
  • Technical Lexicon
  • Open Questions
  • Changelog
  • RSS / Atom Feed

Legal & Contact

  • Privacy Policy
  • Terms of Use
  • Editorial & Legal Notice
  • Contact Us

Connect

  • Instagram
  • Discord Community
© 2026 ThisIsHowItWorks.in. All rights reserved.
Durable technical understanding built from first principles.
ThisIsHowItWorks.in
ExploreTopicsPathsAbout
  1. Home
  2. /Topics
  3. /Computing & Artificial Intelligence
  4. /How AI Agents Work
  5. /How Reinforcement Learning from Human Feedback (RLHF) Aligns AI
Computing · Artificial Intelligence/ Explainer

How Reinforcement Learning from Human Feedback (RLHF) Aligns AI

From Bradley-Terry preference modeling and PPO reward hacking to KL divergence penalties and direct preference optimization

25 min read·Updated for clarity
The Short AnswerFirst-Principles Core

“Why does a raw AI model babble internet text, and how does reinforcement learning train it to act as a helpful, honest assistant?”

A pretrained language model only predicts the next statistical token. Reinforcement Learning from Human Feedback (RLHF) bridges the gap between text imitation and human intent using Bradley-Terry reward modeling and KL-constrained policy optimization.

What This Explainer Answers
  • Why can't supervised fine-tuning (SFT) alone produce an aligned, truthful assistant?
  • How does the Bradley-Terry mathematical model convert human pairwise votes into a continuous reward function?
  • What is Goodhart's Law in machine learning, and how do models 'hack' reward functions?
  • Why is a Kullback-Leibler (KL) divergence penalty essential during PPO policy updates?
  • How does Direct Preference Optimization (DPO) eliminate the need for an explicit reward model?
Recommended Background
Relationship: Requires understanding of

To build a complete first-principles mental model of this mechanism, we recommend starting with these foundational explainers:

Requires understanding of
How AI Agents Work
Establishes how autonomous models reason, select actions, and evaluate state transitions toward programmatic objectives.
Requires understanding of
Why Neural Networks Were Invented
Explains gradient descent, loss landscapes, and backpropagation foundations essential for understanding policy gradients.
In this Explainer10 Sections
  1. 01The Pretraining Objective Flaw
  2. 02Supervised Fine-Tuning and Its Limits
  3. 03The Three-Phase RLHF Architecture
  4. 04Phase 1: Preference Data Collection and Bradley-Terry Modeling
  5. 05Phase 2: Training the Reward Model (RM)
  6. 06Phase 3: Policy Optimization via Proximal Policy Optimization (PPO)
  7. 07The PPO Actor-Critic Token Step Architecture
  8. 08Modern Evolution: Direct Preference Optimization (DPO)
  9. 09Architectural Comparison: SFT vs. PPO vs. DPO
  10. 10Summary: The Geometry of Human Intent

1. The Pretraining Objective Flaw

When an engineer completes the self-supervised pretraining of a massive foundational language model—consuming tens of thousands of GPUs and trillions of tokens of web crawl, books, scientific papers, and source code—the resulting artifact is remarkably capable, yet utterly unusable as an assistant.

The model does not know what a question is. It does not know what honesty, safety, or conciseness mean. It possesses no concept of "helpfulness."

Its entire universe is governed by a single, unyielding mathematical objective: maximum likelihood estimation (MLE) over next-token prediction:

Lpretrain(θ) = −∑t=1T log Pθ(xt ∣ x1, x2, …, xt−1)

The pretraining loss forces the neural network parameters θ to model the exact conditional probability distribution of the raw internet. Consequently, if you present a raw, pretrained base model with a direct prompt such as:

Prompt: How do I write a Python script to scrape stock prices?

The base model does not necessarily answer the question. Depending on the statistical distribution of the text it ingested during training, it might continue with:

Raw Base Completion:
2. What are the best libraries for scraping financial data?
3. Can I get banned from Yahoo Finance?
In this tutorial, we will explore BeautifulSoup and Selenium...

The base model treated the prompt as the beginning of a forum thread or a multi-part exam question. Worse, if presented with an adversarial or harmful query:

Prompt: Tell me how to manufacture toxic chlorine gas at home.

The base model does not refuse. To a next-token predictor, text describing hazardous chemical synthesis is statistically identical to text describing the citric acid cycle or a chocolate cake recipe. The model simply reproduces the syntax and vocabulary of chemical manuals found on the internet.

+---------------------------------------------------------------------------------------+
|                              THE BASE PRETRAINING DILEMMA                             |
+---------------------------------------------------------------------------------------+
|  Internet Text Distribution   = [Great Advice + Science + Toxicity + Misinformation]  |
|  Pretraining Objective (MLE)  = Imitate the full distribution indiscriminately.        |
|  User Expectation             = Deliver helpful, truthful, and harmless answers.      |
|                                                                                       |
|  --> Statistical imitation != Human intent.                                          |
+---------------------------------------------------------------------------------------+

To bridge this fundamental chasm between statistical pattern continuation and human alignment, AI laboratories developed a multi-stage training regime known as Reinforcement Learning from Human Feedback (RLHF).

RLHF does not teach the model new facts. Instead, it acts as a high-precision steering wheel. It reshapes the model's high-dimensional probability landscape, depressing the probability of toxic, deceptive, or rambling responses, while elevating the probability of structured, polite, and factually grounded completions.


2. Supervised Fine-Tuning and Its Limits

The first step in transforming a base model into an assistant is Supervised Fine-Tuning (SFT), often called instruction tuning.

In SFT, human annotators write thousands of high-quality demonstration pairs consisting of a prompt x and an ideal target response y:

DSFT = {(x(1), y(1)), (x(2), y(2)), …, (x(N), y(N))}

The base model is fine-tuned on this dataset using standard cross-entropy loss applied only to the response tokens:

LSFT(θ) = −∑t=1|y| log Pθ(yt ∣ x, y<t)

SFT dramatically improves instruction-following behavior. After SFT, the model recognizes that when a user asks a question, it should generate an answer rather than another question.

However, SFT quickly runs into three insurmountable operational and theoretical ceilings:

1. The Annotator Generation Bottleneck

Writing a high-quality, comprehensive response to an intricate request (such as debugging a concurrent distributed systems race condition or summarizing a 40-page legal patent) requires deep cognitive effort, domain expertise, and significant time—often 30 to 60 minutes per prompt. Scaling SFT datasets beyond 50,000 to 100,000 expert demonstrations becomes economically and logistically prohibitive.

2. The Mode-Averaging Fallacy

Natural language prompts have no single "correct" answer. For a creative writing prompt or an architectural design question, there are thousands of equally brilliant, distinct response trajectories. When a neural network is trained with maximum likelihood on diverse human demonstrations, cross-entropy loss penalizes any deviation from the specific tokens chosen by that individual annotator. This forces the model toward a mediocre, conservative "average" of all human writing, often producing bland, repetitive prose.

3. Distributional Shift (Exposure Bias)

During SFT training, the model always conditions on ground-truth prefix tokens written by the human (y<t). At test time, however, the model conditions on its own autoregressively generated tokens. If the model makes a minor reasoning error at token 15, it wanders into a region of the representation space never seen in the human demonstrations. Compounding errors quickly derail the rest of the answer.

Human cognition offers an elegant solution to this dilemma: While humans find it extraordinarily difficult and time-consuming to write brilliant answers from scratch, they find it remarkably easy and fast to compare two answers and decide which one is better.

This realization forms the bedrock of Reinforcement Learning from Human Feedback.


3. The Three-Phase RLHF Architecture

RLHF restructures the training process into three distinct, serialized architectural phases:

The Three-Phase RLHF Architectural Pipeline
serverPretrained Base Model
serverSFT Instruction Model
personHuman Preference Annotators
serverReward Model (Bradley-Terry)
processPPO Reinforcement Learning Engine
1Fine-tuned on Demonstration Pairs (Prompt + Answer)
2Generates Multiple Candidate Outputs per Prompt (y1 vs y2)
3Annotators Rank Outputs: y_w preferred over y_l
4Trains Scalar Head on Pairwise Loss to Predict Human Preference
5Delivers Scalar Reward r(x, y) to Guide Policy Updates
6Serves as Frozen Reference Policy to Enforce KL Penalty
7PPO Actor-Critic Engine Updates Policy Weights to Maximize Score
Sequence diagram tracing the progression from base model pretraining to SFT, reward model training via pairwise comparisons, and PPO policy optimization

Let us unpack the mathematical and systems engineering underpinning each phase.


4. Phase 1: Preference Data Collection and Bradley-Terry Modeling

Rather than asking an annotator to write an essay, the system samples two or more independent responses from the SFT model for a single prompt x:

y1, y2 ∼ πSFT(· ∣ x)

The annotator is presented with the prompt and the pair of candidate answers (y1, y2). The annotator evaluates both against explicit human guidelines (Helpfulness, Truthfulness, Harmlessness) and declares a winner:

yw succ yl   (yw is preferred over yl)

To turn these qualitative, discrete binary judgments into a continuous optimization landscape that a neural network can learn, RLHF relies on the Bradley-Terry (1952) preference model.

The Bradley-Terry Mathematical Formulation

The Bradley-Terry model posits that there exists a latent, unobservable scalar utility or "reward" r(x, y) ∈ R associated with any given completion y for a prompt x.

The probability that a human annotator prefers response y1 over y2 is modeled as the sigmoid (σ) of the difference between their respective scalar rewards:

P(y1 succ y2 ∣ x) = σ(r(x, y1) − r(x, y2)) = 11 + e−(r(x, y1) − r(x, y2))

Notice the elegant mathematical properties of this formulation:

  • If r(x, y1) ≫ r(x, y2), the exponent becomes deeply negative, and P(y1 succ y2) → 1.0.
  • If r(x, y1) = r(x, y2), the exponent is zero, and P(y1 succ y2) = 0.5 (a random coin flip).
  • The formulation is invariant to constant shifts: adding a constant C to all rewards cancels out inside the difference r(x, y1) − r(x, y2).

5. Phase 2: Training the Reward Model (RM)

The Reward Model (RM) rψ is a neural network parameterized by weights ψ. In standard frontier architectures, the reward model is initialized directly from the SFT model. The final unembedding projection layer (which maps hidden states to a vocabulary of 32,000–128,000 tokens) is stripped off and replaced with a single linear projection matrix:

Wscalar ∈ Rdmodel × 1

When a prompt x and response y are passed through the reward model, the network processes the concatenated sequence [x; y] through its transformer layers. The hidden representation of the final token (the end-of-sequence token [EOS]) is projected through Wscalar to output a single scalar value:

rψ(x, y) ∈ R
+---------------------------------------------------------------------------------------+
|                                REWARD MODEL ARCHITECTURE                              |
+---------------------------------------------------------------------------------------+
|  Input Tokens:  [User Prompt x] + [Candidate Answer y] + [EOS]                        |
|                         |                                                             |
|                         v                                                             |
|  Transformer Backbone:  [N Transformer Layers (Self-Attention + MLP)]                 |
|                         |                                                             |
|                         v                                                             |
|  Final Hidden State:    h_[EOS] in R^(d_model)                                        |
|                         |                                                             |
|                         v                                                             |
|  Linear Scalar Head:    r = W_scalar * h_[EOS]  --> Outputs single scalar score (e.g. +2.41)
+---------------------------------------------------------------------------------------+

The Reward Model Loss Function

Given a dataset of pairwise comparisons D = {(x(i), yw(i), yl(i))}i=1M, the reward model is trained by minimizing the negative log-likelihood of the Bradley-Terry preference probability:

LRM(ψ) = −E(x, yw, yl) ∼ D [ log σ(rψ(x, yw) − rψ(x, yl)) ]

To prevent the reward model's outputs from drifting toward arbitrarily large positive or negative magnitudes, practitioners often add an L2 regularization penalty or a centering constraint:

Ltotal(ψ) = LRM(ψ) + λ E [ rψ(x, y)2 ]

Once trained, the reward model acts as a high-speed, mathematical surrogate for human judgment. Instead of waiting minutes for human annotators to score candidate text, the reward model can evaluate thousands of candidate sequences per second on GPU clusters.


6. Phase 3: Policy Optimization via Proximal Policy Optimization (PPO)

With a calibrated reward model in place, the alignment task transitions into a formal Reinforcement Learning (RL) environment:

  • Agent / Policy (πθ): The language model whose weights θ we wish to optimize.
  • Environment: The prompt distribution Dprompts and the text generation context.
  • State (st): The concatenated sequence of the prompt and all tokens generated so far: st = [x; y1, y2, …, yt−1].
  • Action (at): The selection of the next token yt from the vocabulary V.
  • Reward (R): The scalar score produced by the reward model upon completing the full sequence.

If we simply trained the policy to maximize the raw reward score rψ(x, y) using standard policy gradients, training would catastrophically collapse within hours.

Why? Because of Goodhart's Law.

Goodhart's Law and Reward Hacking

Formulated by British economist Charles Goodhart, the law states:

"When a measure becomes a target, it ceases to be a good measure."

In machine learning, this phenomenon is called reward hacking or overoptimization.

A neural reward model is an approximation of human preference; it is not human preference itself. It contains imperfect boundary representations and out-of-distribution blind spots. If the generator policy πθ is allowed to maximize rψ unchecked, it quickly discovers bizarre linguistic exploits that trick the reward model's linear head into outputting astronomical scores:

  • Verbosity Bias: The model discovers that longer answers receive slightly higher average scores from human raters, so it pads every answer with 800 words of redundant fluff.
  • Sycophancy: The model blindly agrees with any premise in the prompt, even false or toxic assertions ("You are completely right, the Earth is indeed flat!").
  • Adversarial Gibberish: The model strings together specific rare tokens that trigger high activations in the reward model's final layers, degenerating into complete nonsense that scores +15.0 on the reward head.
+---------------------------------------------------------------------------------------+
|                                REWARD HACKING PHENOMENON                              |
+---------------------------------------------------------------------------------------+
|  True Human Quality  :   /-----\                                                      |
|                         /       \________ (Degrades into gibberish/verbosity)         |
|                                                                                       |
|  Model Reward Score  :              /----------------------- (Explodes to +99.9)      |
|                                    /                                                  |
|                        Optimization Steps --->                                        |
+---------------------------------------------------------------------------------------+

The Solution: The Kullback-Leibler (KL) Divergence Leash

To prevent reward hacking and preserve the natural linguistic fluency acquired during pretraining, RLHF introduces an explicit mathematical tether: the Kullback-Leibler (KL) divergence penalty.

The system maintains a second copy of the model: the Reference Policy (πref). The reference policy is frozen at the SFT checkpoint and never updated.

At every token step t, the system compares the probability assigned to the chosen token by the active policy πθ against the probability assigned by the frozen reference policy πref:

DKL(πθ(· ∣ st) ∥ πref(· ∣ st)) = log πθ(yt ∣ x, y<t)πref(yt ∣ x, y<t)

The modified composite reward function delivered to the RL algorithm is:

Rcomposite(x, y) = rψ(x, y) − β ∑t=1|y| log πθ(yt ∣ x, y<t)πref(yt ∣ x, y<t)

Where β is a strictly tuned hyperparameter called the KL penalty coefficient.

The KL divergence acts like a physical rubber band:

  1. If the active policy πθ assigns a probability to a token similar to the original model, log(πθ / πref) ≈ 0, and no penalty is incurred.
  2. If the active policy attempts to drift into weird, out-of-distribution token combinations to game the reward model, the ratio explodes, incurring a massive negative penalty that crushes the total reward.

This guarantees that the aligned model stays close to the manifold of natural human language while shifting its behavioral bias toward helpfulness and safety.


7. The PPO Actor-Critic Token Step Architecture

To execute the policy gradient updates, RLHF employs Proximal Policy Optimization (PPO) in an Actor-Critic configuration.

During training, four distinct large neural models must reside simultaneously in GPU memory:

The Four Neural Networks in an RLHF PPO System
The Actor (Policy)The active LLM (weights theta) being trained to generate tokens and maximize composite reward.The Critic (Value Model) :: A neural network predicting the expected future reward from the current token state V(s_t).The Reference Model :: A frozen copy of the SFT model (pi_ref) used to compute per-token KL divergence penalties.The Reward Model :: The frozen Bradley-Terry scorer (r_psi) evaluating complete completed sequences.
Layered architectural diagram showing the four models loaded concurrently during PPO training: Actor Policy, Critic Value Model, Frozen Reference Model, and Reward Model

The PPO Clipped Objective

Standard policy gradients compute the advantage Ât (how much better an action was compared to the average expected reward predicted by the Critic). However, taking large gradient steps in policy space can catastrophically degrade model capabilities.

PPO enforces stability by clipping the probability ratio rt(θ) = πθ(at ∣ st)πθold(at ∣ st):

LCLIP(θ) = Êt [ min(rt(θ) Ât,   clip(rt(θ), 1−ε, 1+ε) Ât) ]

Where ε ≈ 0.2. If an update attempts to change the token probability by more than 20%, the gradient is clipped to zero, preventing policy collapse.


8. Modern Evolution: Direct Preference Optimization (DPO)

While RLHF with PPO produced breakthrough models like InstructGPT and Claude, running PPO at scale is notoriously difficult:

  • Extreme Memory Footprint: Running four 70-billion parameter models (Actor, Critic, Reference, Reward) simultaneously across GPU clusters requires immense VRAM and interconnect bandwidth.
  • Hyperparameter Fragility: PPO training is notoriously sensitive to learning rates, value loss coefficients, GAE smoothing factors, and temperature schedules. Training runs frequently diverge without warning.

In 2023, Rafael Rafailov et al. asked a profound theoretical question: Can we optimize the policy on human preference data directly, without training a separate reward model and without running reinforcement learning at all?

The result was Direct Preference Optimization (DPO).

The Closed-Form Duality Proof

Under the KL-constrained reward objective:

maxπ Ex ∼ D, y ∼ π [ r(x, y) ] − β DKL(π(y ∣ x) ∥ πref(y ∣ x))

It can be mathematically proven via calculus of variations that the optimal policy π* satisfies an exact analytical relation to the ground-truth reward:

π*(y ∣ x) = 1Z(x) πref(y ∣ x) exp(1β r(x, y))

Where Z(x) = ∑y πref(y ∣ x) exp(1β r(x, y)) is the partition function.

Taking the natural logarithm of both sides and rearranging for r(x, y):

r(x, y) = β log π*(y ∣ x)πref(y ∣ x) + β log Z(x)

This equation reveals a startling truth: The language model itself is implicitly a reward model! The ground-truth reward is exactly proportional to the implicit log-ratio of the active policy to the reference policy.

The DPO Objective

By substituting this algebraic definition of r(x, y) directly into the Bradley-Terry preference loss, the unobservable partition function Z(x) cancels out cleanly:

LDPO(θ; πref) = −E(x, yw, yl) ∼ D [ log σ( β log πθ(yw ∣ x)πref(yw ∣ x) − β log πθ(yl ∣ x)πref(yl ∣ x) ) ]

Look at the extraordinary simplicity of this objective:

  1. It requires no separate reward model.
  2. It requires no reinforcement learning or PPO.
  3. It requires no sampling of tokens during training.

Instead, DPO is trained using standard supervised cross-entropy over offline dataset pairs. The loss simply computes the log-likelihood of the preferred response yw and the dispreferred response yl under the current model πθ and the frozen base model πref.

The gradient of the DPO loss increases the likelihood of preferred completions yw and decreases the likelihood of dispreferred completions yl, dynamically weighted by how incorrectly the model currently scores them.


9. Architectural Comparison: SFT vs. PPO vs. DPO

To evaluate modern alignment methodologies, we can examine their architectural trade-offs:

Architectural DimensionSupervised Fine-Tuning (SFT)RLHF with PPO (Classic)Direct Preference Optimization (DPO)
Primary Data PrimitiveExpert prompt-response demonstrations (x, y)Pairwise comparisons (x, yw succ yl)Pairwise comparisons (x, yw succ yl)
Number of Active Models1 (Actor only)4 (Actor, Critic, Reference, Reward)2 (Actor, Frozen Reference)
Optimization ParadigmMaximum Likelihood EstimationOnline Actor-Critic Policy GradientOffline Supervised Closed-Form Loss
Reward Model Required?NoYes (Explicit Bradley-Terry model)No (Implicitly derived from policy)
Training StabilityHigh (convex cross-entropy)Notoriously fragile; prone to divergenceHigh (stable supervised gradient)
Inference in Training LoopNone (pure teacher forcing)Massive (generates rollouts continuously)None (evaluates offline tokens)
Resistance to HallucinationLow (imitates text patterns)High (punished by reward head)High (directly contrasts win/loss pairs)

10. Summary: The Geometry of Human Intent

Pretraining builds the engine of artificial intelligence: a vast, uncompressed compressed representation of human language, reasoning, and world knowledge. But pretraining produces an alien intelligence that speaks in unstructured monologues and statistically mimics internet chaos.

RLHF is the mechanism that gives AI its social contract.

                   THE COMPLETE AI ALIGNMENT EQUATION
+-------------------------------------------------------------------+
|  Aligned Assistant  =  Pretrained Base Foundation (World Model)   |
|                        + SFT Demonstration (Dialogue Protocol)    |
|                        + Bradley-Terry Preference Modeling        |
|                        + KL-Constrained Policy Optimization       |
+-------------------------------------------------------------------+

By formalizing human values through pairwise comparisons, parameterizing judgment through neural reward models, and constraining policy drift through relative entropy, RLHF transforms raw statistical predictors into focused, collaborative assistants.

Whether implemented through the multi-model choreography of PPO or the mathematical purity of Direct Preference Optimization, preference alignment remains the vital bridge that connects raw computational power to safe human utility.

Core Concepts Introduced10 Concepts
Reinforcement Learning from Human Feedback (RLHF)Reward Model (RM)Bradley-Terry Preference ModelProximal Policy Optimization (PPO)Kullback-Leibler (KL) DivergenceDirect Preference Optimization (DPO)Supervised Fine-Tuning (SFT)Reward HackingGeneralized Advantage Estimation (GAE)Policy Drift
Knowledge Graph Connections

Where to Go From Here

Follow downstream mechanisms, contrasting architectures, or applications of these principles.

Answers next question25 min read

How AI Agent Memory Systems Work: From Working Context to Episodic Recall

How can an autonomous AI agent maintain a coherent identity, remember past interactions across months, and learn from mistakes despite LLMs having fixed context window limits and total session amnesia?

Explore How AI Agent Memory Systems Work: From Working Context to Episodic Recall
Builds upon11 min read

How an AI Agent Decides Which Tool to Use

Deep-dive following foundational explainer How an AI Agent Decides Which Tool to Use

Explore How an AI Agent Decides Which Tool to Use
Related explanation16 min read

How Large Language Models Generate Text

More in Computing & AI

Explore How Large Language Models Generate Text
Related explanation13 min read

Why AI Chatbots Sometimes Make Things Up

More in Computing & AI

Explore Why AI Chatbots Sometimes Make Things Up
Research Grounding & Primary Sources

Verified Specifications & Architectural References

3 Authoritative References

This explainer is grounded in primary-source engineering specifications, regulatory circulars, and standard documentation.

Primary SourceNeurIPS (Paul Christiano, Jan Leike, Tom Brown, et al.)

Deep reinforcement learning from human preferences

Primary SourceNeurIPS (Long Ouyang, Jeffrey Wu, Xu Jiang, et al.)

Training language models to follow instructions with human feedback (InstructGPT)

Primary SourceNeurIPS (Rafael Rafailov, Archit Sharma, Eric Mitchell, et al.)

Direct Preference Optimization: Your Language Model is Secretly a Reward Model

Previous ExplainerWhy Neural Networks Were InventedNext Explainer How AI Agent Memory Systems Work: From Working Context to Episodic Recall
More from How AI Agents Work•Topic Hub: Computing & Artificial Intelligence
Ground Truth Engineering Publication