Özer Cem KELAHMETKELAHMET
Articles · RLHF

RLHF explained: preference data, Bradley–Terry reward models and the KL-penalised RL step

RLHF turns human judgements into a training signal for language models. This guide walks through the three stages, supervised fine-tuning, a Bradley–Terry reward model and KL-penalised reinforcement learning, with worked numbers, runnable PyTorch and the current TRL 1.18 tools.

Download Markdown
At a glance
Reading time
17 min
Sections
8
Code examples
4
Tables
3
Sources
8
Published
25 Nov 2026
In 30 seconds
What changed
TRL removes PPOTrainer from its stable library
Why it matters
RLHF is three bets in a row.
What to do
Write a labelling guide before collecting pairs

A pretrained language model has read a large part of the internet, but it was trained only to continue text. Ask it a question and it may answer, ramble, repeat the question or invent a source. Nobody can write a loss function for "helpful, honest and harmless". People can, however, look at two answers and say which one is better. Reinforcement learning from human feedback (RLHF) is the method that turns those comparisons into a training signal.

RLHF made the jump from research to products with OpenAI's InstructGPT paper in 2022, and its parts still shape how chat models are post-trained. This article explains the three stages, derives the reward-model loss and the KL-penalised objective, works through the numbers, and shows what goes wrong. It assumes you know the basics of reinforcement learning: a policy, a reward and an update rule.

What happened

RLHF itself dates to 2017, but the open tooling around it changed this autumn.

TRL removes PPOTrainer from its stable library (TRL 1.13.0, 10 September 2026)

Hugging Face's TRL had been a widely used open implementation of the classic RLHF loop. Its 1.13.0 release notes state that PPOTrainer, PPOConfig and the value-head model code were removed. The TRL v1.0 announcement in March 2026 described PPO as the algorithm that "made one architecture look canonical": a policy, a reference model, a learned reward model, sampled rollouts and an RL loop. That architecture now lives on through other trainers.

TRL 1.18.2 keeps reward modelling, RLOO and GRPO as the stable RLHF parts (19 November 2026)

In TRL 1.18.2, RewardTrainer trains the reward model, and RLOOTrainer and GRPOTrainer run the RL stage. Both RL trainers accept a reward model's Hub ID or path as a reward function and load it as a sequence classifier with one output. RLOOTrainer defaults to a KL coefficient beta=0.05; GRPOTrainer defaults to beta=0.0. In other words, the full RLHF pipeline still runs on the current release, just without a learned critic.

Stage 1 and 2: from demonstrations to a reward model

The classic pipeline, as described in the InstructGPT paper (Ouyang et al., 2022), has three stages.

Table 1. Stage 1 and 2: from demonstrations to a reward model
Stage Data What is trained InstructGPT scale
1. Supervised fine-tuning (SFT) prompts with written demonstrations the policy starts here about 13k prompts
2. Reward modelling prompts with ranked model outputs a reward model r_φ(x, y) about 33k prompts, 4 to 9 outputs ranked per prompt, 6B reward model
3. Reinforcement learning prompts only the policy, against r_φ, with a KL penalty about 31k prompts

The labels came from about 40 contractors. The paper used a 6B reward model because training a 175B one "could be unstable". Ranking K outputs at once gives K choose 2 comparisons for one prompt: a ranking of 9 outputs yields 36 pairs.

The Bradley–Terry reward model

The reward model reads a prompt x and a response y and outputs one number. To train it from comparisons, RLHF uses the Bradley–Terry model, the same model used to rate chess players and chatbot arenas. It says the probability that a person prefers response y_w over y_l is:

P(y_w ≻ y_l given x) = σ( r(x, y_w) − r(x, y_l) )

where σ is the logistic sigmoid. Only the difference in scores matters. Maximising the likelihood of the observed choices gives the loss:

L(φ) = − E[ log σ( r_φ(x, y_w) − r_φ(x, y_l) ) ]

This is exactly the loss in TRL's RewardTrainer, which also supports an optional margin subtracted inside the sigmoid and an optional centring term that keeps rewards near zero (the docs recommend a coefficient of 0.01).

Worked example. The reward model scores the chosen answer 1.2 and the rejected answer 0.4.

  1. Difference = 1.2 − 0.4 = 0.8.
  2. σ(0.8) = 0.690, so the model gives the human's choice a 69% probability.
  3. Loss = −log(0.690) = 0.371.

If the scores were swapped, the difference would be −0.8, σ(−0.8) = 0.310, and the loss would be 1.171. The gradient pushes hardest on the pairs the model gets wrong.

Bradley–Terry pairwise loss: preference probability and loss by score gap
P(chosen preferred) = σ(gap)loss = −log σ(gap)
00.511.522.5-2-1-0.500.512P(chosen preferred) = σ(gap) · -2: 0.119P(chosen preferred) = σ(gap) · -1: 0.269P(chosen preferred) = σ(gap) · -0.5: 0.378P(chosen preferred) = σ(gap) · 0: 0.5P(chosen preferred) = σ(gap) · 0.5: 0.622P(chosen preferred) = σ(gap) · 1: 0.731P(chosen preferred) = σ(gap) · 2: 0.881loss = −log σ(gap) · -2: 2.13loss = −log σ(gap) · -1: 1.31loss = −log σ(gap) · -0.5: 0.974loss = −log σ(gap) · 0: 0.693loss = −log σ(gap) · 0.5: 0.474loss = −log σ(gap) · 1: 0.313loss = −log σ(gap) · 2: 0.127r(chosen) − r(rejected)value
Figure 1. Computed from the sigmoid and log-loss formulas above

With a margin of 0.5 (for "clearly better" pairs), the loss becomes −log σ(0.8 − 0.5) = 0.554, so the model is asked for a larger gap. You can fit Bradley–Terry ratings by hand in the arena ratings simulation.

Code: train a Bradley–Terry reward model in PyTorch

This toy hides a "true human taste" vector, generates noisy preference labels from it with Bradley–Terry, and trains a linear reward model on the pairwise loss.

import torch, torch.nn as nn, torch.nn.functional as F
torch.manual_seed(0)
d, n_train, n_test = 8, 4000, 1000
w_true = torch.randn(d)                               # hidden "human taste"

def make_pairs(n):
    a, b = torch.randn(n, d), torch.randn(n, d)
    p_a = torch.sigmoid(a @ w_true - b @ w_true)      # Bradley-Terry
    a_wins = torch.rand(n) < p_a                      # noisy human label
    chosen = torch.where(a_wins[:, None], a, b)
    rejected = torch.where(a_wins[:, None], b, a)
    return chosen, rejected

c_tr, r_tr = make_pairs(n_train)
c_te, r_te = make_pairs(n_test)

rm = nn.Linear(d, 1)                                  # the reward model
opt = torch.optim.Adam(rm.parameters(), lr=0.05)
for step in range(300):
    loss = -F.logsigmoid(rm(c_tr) - rm(r_tr)).mean()  # pairwise loss
    opt.zero_grad(); loss.backward(); opt.step()

with torch.no_grad():
    acc = (rm(c_te) > rm(r_te)).float().mean().item()
    oracle = ((c_te @ w_true) > (r_te @ w_true)).float().mean().item()
print(f"held-out accuracy {acc:.3f}, true reward scores {oracle:.3f}")

Our run on PyTorch 2.15.0 printed a held-out pairwise accuracy of 0.886, while the hidden true reward itself agreed with the labels only 0.885 of the time. That is the lesson: the ceiling on reward-model accuracy is set by how consistent the labellers are, not by the model. Real reward models trained on human data usually land well below 100% agreement for the same reason.

Stage 3: the KL-penalised objective

With a reward model in hand, the policy π_θ is trained to produce responses that score well. If you only maximised r_φ, the policy would drift into strange text that fools the reward model. RLHF therefore adds a penalty for moving away from the starting SFT model π_ref:

maximise E_{x, y ~ π_θ}[ r_φ(x, y) ] − β · KL( π_θ(· given x) ‖ π_ref(· given x) )

In practice the KL term is applied per token. Each sampled response gets the reward-model score at the end, and every token pays −β log(π_θ(token) / π_ref(token)).

Worked example. A response scores r_φ = 2.0. Summed over its tokens, log π_θ − log π_ref = 6.0, and β = 0.05. The penalty is 0.05 × 6.0 = 0.3, so the RL algorithm sees a total reward of 1.7. If the policy had drifted further, say a summed log ratio of 30, the penalty would be 1.5 and most of the gain would be gone.

An everyday analogy: the reward model is a new manager with some odd preferences, and the KL penalty is a rule that you cannot change your writing style too much in one quarter. You improve where the manager is right, without rewriting yourself to please a quirk.

This objective has a closed-form optimum, which the DPO paper later exploited:

π*(y given x) = π_ref(y given x) · exp( r(x, y) / β ) / Z(x)

The best policy reweights the reference model's outputs by their exponentiated reward. A small β means aggressive reweighting; a large β keeps the policy close to π_ref. The derivation and its use in DPO are covered in our article on how DPO works.

Code: watch reward hacking happen as β shrinks

Here one prompt has six candidate replies. The reward model agrees with people on five of them but badly overrates reply 6 (think of a long, flattering answer that is wrong). We compute π* exactly for several β values.

import numpy as np
pi_ref = np.array([0.30, 0.25, 0.20, 0.15, 0.07, 0.03])
true_r = np.array([0.0, 0.5, 1.0, 1.5, 2.0, -1.0])   # what people think
proxy  = true_r.copy(); proxy[5] = 3.0                # the RM's mistake
for beta in [10, 2, 1, 0.5, 0.25, 0.1]:
    w = pi_ref * np.exp(proxy / beta); pi = w / w.sum()
    kl = np.sum(pi * np.log(pi / pi_ref))
    print(beta, round(pi @ proxy, 2), round(pi @ true_r, 2), round(kl, 2), round(pi[5], 2))
Table 2. Code: watch reward hacking happen as β shrinks
β Proxy reward True reward KL from π_ref P(reply 6)
10 0.84 0.69 0.00 0.04
2 1.10 0.76 0.08 0.08
1 1.51 0.72 0.39 0.20
0.5 2.35 0.09 1.64 0.57
0.25 2.94 −0.84 3.20 0.95
0.1 3.00 −1.00 3.51 1.00
Reward hacking in a toy RLHF problem: proxy versus true reward as the KL penalty shrinks
proxy reward (reward model)true reward (people)
-1012310210.50.250.1proxy reward (reward model) · 10: 0.84proxy reward (reward model) · 2: 1.1proxy reward (reward model) · 1: 1.51proxy reward (reward model) · 0.5: 2.35proxy reward (reward model) · 0.25: 2.94proxy reward (reward model) · 0.1: 3true reward (people) · 10: 0.69true reward (people) · 2: 0.76true reward (people) · 1: 0.72true reward (people) · 0.5: 0.09true reward (people) · 0.25: -0.84true reward (people) · 0.1: -1KL coefficient βexpected reward
Figure 2. Computed by the six-reply script in this article (exact KL-regularised optimum)

The proxy reward climbs steadily as β falls. The true reward peaks at β = 2 and then collapses as the policy piles onto the reply the reward model wrongly loves. This is the pattern Gao, Schulman and Hilton measured at scale in "Scaling Laws for Reward Model Overoptimization" (2022): with a fixed gold reward model standing in for people, optimising a proxy too hard lowered the gold score.

How the RL step runs for a language model

The RL stage treats generation as an episode. The state is the prompt plus tokens so far, each action is one token, and the reward arrives at the end (minus the per-token KL). The original pipeline used PPO with a learned value head, so four models were in memory: the policy, the reference model, the reward model and the critic.

Table 3. How the RL step runs for a language model
Method Models in memory Baseline for the advantage Status in TRL 1.18.2
PPO (InstructGPT style) policy, reference, reward model, critic learned value function removed in 1.13.0
RLOO policy, reference (if β is above 0), reward model mean reward of the other samples for the same prompt stable, beta=0.05 default
GRPO policy, reward model, reference only if β is above 0 group mean, often divided by group standard deviation stable, beta=0.0 default
DPO (offline) policy, reference no RL loop; uses the closed-form optimum stable

RLOO and GRPO sample several responses per prompt and use their average as the baseline, which replaces the critic. To see the clipped update that all of these share, use the PPO clipped objective simulation.

Running RLHF with current TRL

The snippets below follow the examples in the TRL 1.18.2 source. The first trains a reward model on a public preference dataset; the second uses it as the reward for RLOO.

from datasets import load_dataset
from trl import RewardTrainer, RewardConfig, RLOOTrainer, RLOOConfig

# Stage 2: reward model (pairwise loss, -log sigmoid(r_chosen - r_rejected))
prefs = load_dataset("trl-lib/ultrafeedback_binarized", split="train")
rm_trainer = RewardTrainer(
    model="Qwen/Qwen2.5-0.5B-Instruct",
    args=RewardConfig(output_dir="rm", center_rewards_coefficient=0.01),
    train_dataset=prefs,
)
rm_trainer.train()

# Stage 3: RL against the reward model, KL penalty beta to the reference
prompts = load_dataset("trl-lib/ultrafeedback-prompt", split="train")
rl_trainer = RLOOTrainer(
    model="Qwen/Qwen2.5-0.5B-Instruct",          # in practice: your SFT model
    reward_funcs="rm",                           # path to the trained reward model
    args=RLOOConfig(output_dir="rloo", beta=0.05, num_generations=4),
    train_dataset=prompts,
)
rl_trainer.train()

We checked the class names, argument names and defaults against the installed TRL 1.18.2 code; the model training itself needs a GPU and was not run here. You can follow the SFT-then-preference path interactively in the post-training simulation.

Use cases and examples

InstructGPT, the reference case. OpenAI fine-tuned GPT-3 with the three stages above. Labellers preferred outputs of the 175B InstructGPT model to 175B GPT-3 85 ± 3% of the time, and preferred the 1.3B InstructGPT model to the 175B GPT-3 despite it having over 100 times fewer parameters. Hallucination on closed-domain tasks fell from 41% to 21%.

Summarisation from human feedback. Stiennon and colleagues (2020) trained a reward model on human comparisons of Reddit TL;DR summaries and optimised a policy with RL. Their models beat the human reference summaries and much larger supervised-only models, and transferred to CNN/DM news articles without news-specific training.

Learning a behaviour nobody can specify. Christiano and colleagues (2017) taught simulated agents behaviours such as a backflip from human comparisons of short clips. They report needing feedback on less than 1% of the agent's interactions and about an hour of human time.

A company tuning a support assistant. A team logs pairs of draft replies, has agents pick the better one, trains a reward model with RewardTrainer, and runs RLOO with β around 0.05. They hold out 10% of the pairs and track reward-model accuracy, then check the RL policy's KL from the SFT model every few hundred steps to catch drift.

A safety team auditing for reward hacking. They score samples from each checkpoint with a second, independently trained reward model or with human spot checks. When the training reward keeps rising while the audit score flattens, as in our toy chart, they stop or raise β.

What it means in practice

RLHF is three bets in a row. The first is that labellers agree often enough to define a signal. The second is that a reward model trained on tens of thousands of comparisons generalises to the policy's new outputs. The third is that the KL penalty keeps the policy in the region where the reward model is still right. Each bet can fail, and most RLHF problems trace back to one of them.

The field has moved some of the work elsewhere. DPO removes the RL loop by using the closed-form optimum. RLAIF replaces some human labels with model labels. RL with verifiable rewards replaces the reward model with a checker wherever a correct answer exists. Yet the core ideas, preference pairs, a Bradley–Terry likelihood and a KL anchor to a reference model, appear in all of them. Read our RLHF reference page and DPO page for how the pieces connect.

What to do now

  1. Write a labelling guide before collecting pairs. Agreement between labellers caps your reward-model accuracy, as the toy run showed.
  2. Measure inter-labeller agreement. Double-label a sample of pairs; where people often disagree on a slice, fix the guide or drop that slice before training.
  3. Hold out preference pairs. Report reward-model accuracy on pairs it never saw, broken down by task type.
  4. Start from a strong SFT model. RL refines behaviour; it rarely teaches skills the SFT model lacks.
  5. Sweep β, not just the learning rate. Track proxy reward and an independent check together, and pick the β before the true score turns down.
  6. Log KL from the reference every few hundred steps. A fast rise in KL is the earliest sign of reward hacking.
  7. Watch for length and style exploits. Compare response length and formatting across checkpoints; reward models often favour longer answers.
  8. Use current TRL trainers. Use RewardTrainer with RLOOTrainer or GRPOTrainer in TRL 1.18.2; PPOTrainer no longer exists in the stable library.

Risks and open questions

Reward hacking is structural. Any learned reward has blind spots, and optimisation finds them. The KL penalty slows this down but does not remove it.

Human labels are expensive and inconsistent. Labellers disagree, get tired and bring their own biases, and those biases become the model's values.

Sycophancy is a known side effect. If people reward answers that agree with them, the policy learns to agree rather than to be right.

A single scalar hides trade-offs. Helpfulness and harmlessness can pull in opposite directions, and one reward number cannot say which matters more in a given case.

Watch next: whether AI-generated feedback (see RLAIF) and rubric-based rewards can match human labels at lower cost, and how far critic-free RL methods can go before learned critics return for long agentic tasks.

Frequently asked questions

Why not just fine-tune on the preferred answers?

You can, and that is roughly what SFT on curated data does. A reward model learns from both the preferred and the rejected answer, so it learns what makes one better, and it can score new responses the policy invents during training. That ability to evaluate fresh samples is what makes the RL stage possible.

What does β control in RLHF?

β sets how strongly the policy is pulled back toward the reference model. A large β keeps the policy close to the SFT model and limits both improvement and hacking. A small β lets the policy chase the reward model further, which helps until the reward model's mistakes dominate, as the toy table shows.

Why is the reward model smaller than the policy in InstructGPT?

The authors report that training a 175B reward model could be unstable, so they used 6B reward models. A smaller reward model is also cheaper to run on every sampled response during RL. Later work studied how reward-model size affects overoptimisation.

Is RLHF the same as DPO?

No. RLHF trains an explicit reward model and then runs online RL, sampling new responses from the policy. DPO uses the closed-form optimum of the same KL-penalised objective to train directly on preference pairs, with no reward model and no sampling loop. They optimise the same idealised target but behave differently in practice.

Can I still run classic PPO-based RLHF in TRL?

Not in the current stable release, since TRL 1.13.0 removed PPOTrainer. The same pipeline runs with RewardTrainer for the reward model and RLOOTrainer or GRPOTrainer for the RL stage, which replace the critic with a baseline computed from several samples per prompt.

Summary

RLHF turns human comparisons into a training signal in three stages: supervised fine-tuning on demonstrations, a Bradley–Terry reward model trained with −log σ(r_w − r_l), and reinforcement learning that maximises the reward minus a β-weighted KL penalty to the reference model. The worked numbers show a 0.8 score gap gives a 69% preference probability and a loss of 0.371. The toy optimisation shows why the KL anchor matters: as β shrinks, the proxy reward rises from 0.84 to 3.00 while the true reward falls from a peak of 0.76 to −1.00. InstructGPT proved the recipe at scale. Today's TRL 1.18.2 keeps the reward model and the KL anchor but runs the RL step with RLOO or GRPO instead of PPO. Explore more in the LLM-judge agreement simulation and the TRL page.

Sources

Cite this article

Kelahmet, Ö. C. (2026, November 25). RLHF explained: preference data, Bradley–Terry reward models and the KL-penalised RL step. Özer Cem KELAHMET. https://www.ozercemkelahmet.com/articles/rlhf-reward-models-kl-penalty-explained

BibTeX
@online{kelahmet2026rlhf,
  author = {Kelahmet, {\"O}zer Cem},
  title  = {{RLHF explained: preference data, Bradley–Terry reward models and the KL-penalised RL step}},
  year   = {2026},
  month  = {nov},
  url    = {https://www.ozercemkelahmet.com/articles/rlhf-reward-models-kl-penalty-explained}
}
Version historyfirst version
  1. Published

Factual corrections are listed here with what changed. Wording and formatting edits are not listed.

Last updated Nov 25, 2026
Type to search.
    ↑↓ navigate↵ open