By Sagi Shaier · 26 November 2026 · 12 min read
RLHF explained
How people's picks between two answers become a learned score, how that score trains a chat assistant without letting it drift too far, and what the scoring model's loss looks like in PyTorch.
Reinforcement learning from human feedback (RLHF) trains a language model on people's judgments of which answer is better. In many chat assistants it is the training step that comes after supervised fine-tuning. It shapes how the model answers requests that have many acceptable replies, where no single written example says which reply is best.
Language models read and write text as tokens, which are whole words or pieces of words. A model is first pretrained to predict the next token over a huge amount of text. It then goes through supervised fine-tuning (SFT), where it trains on written examples of a request and a good response. RLHF starts from that SFT model.
What SFT leaves out
SFT gives the model one answer to imitate for each prompt. For an open-ended prompt, several answers can be acceptable. One may be clearer and another too long. A third may sound confident but be wrong, and a fourth may refuse a harmless request. A single demonstration says "write something like this" and does not say which nearby answers are worse, or why.

Why compare answers instead of writing them?
Preference learning adds that missing contrast. A labeler is the person giving the judgments. Instead of asking the labeler to write one ideal response, you show them candidate answers and ask which one better satisfies the request.
Judging can be easier than writing, especially for hard or open-ended prompts. The labeler compares what is already there: clear against vague, correct against unsupported, and a helpful answer against a refusal nobody needed.

Comparisons also tend to agree more across people. Ask three raters to score one response from 1 to 10 and one may give it a 7 while another gives it a 4. The same person can also drift over a long session. Asking which of two responses is better is often more stable, because nobody has to agree on what the numbers on a scale mean.

What preference data looks like
Many preference methods train on records with three parts: a prompt, one response labeled chosen and another labeled rejected. The labeler did not have to see exactly two options. They may have given a thumbs up or down, picked the best of several or sorted a few candidates into a ranking. Each of those judgments can be turned into chosen and rejected pairs.

A ranking gives the most pairs. If $N$ responses are ranked, each higher-ranked response is preferred to each lower-ranked one, which gives $N(N-1)/2$ pairs. For five responses that is $5 \times 4 / 2 = 10$ pairs from one annotation:
1from itertools import combinations
2
3ranked = ["r1", "r2", "r3", "r4", "r5"] # best first, as a labeler ordered them
4
5pairs = [{"chosen": a, "rejected": b} for a, b in combinations(ranked, 2)]
6print(len(pairs), "pairs")
7print(pairs[0])
8print(pairs[-1])110 pairs
2{'chosen': 'r1', 'rejected': 'r2'}
3{'chosen': 'r4', 'rejected': 'r5'}combinations(ranked, 2) keeps the list order inside each pair, so the higher-ranked response always comes first and becomes the chosen one.

Here is one finished record, for the prompt "Explain dropout to a beginner in two sentences":
1record = {
2 "prompt": "Explain dropout to a beginner in two sentences.",
3 "chosen": "Dropout randomly hides some neuron outputs during training, so the network "
4 "cannot rely too much on any one feature. This usually helps it generalize "
5 "better to new examples.",
6 "rejected": "Dropout means the model deletes bad data points before training.",
7}
8print(list(record))1['prompt', 'chosen', 'rejected']The record does not claim the chosen answer is the only good one. It says that for this prompt, people preferred it over this particular alternative.

Preference labels often come from people comparing outputs. Sometimes another model does part of the judging, a setup called reinforcement learning from AI feedback (RLAIF). Some preference signals already exist on the web too. Vote counts on a question-and-answer site give a noisy ordering of the answers to each question.

The reward model is a learned judge
People can judge answers, but asking them to judge every new response during training would be slow and expensive. The model being trained writes new responses each time its weights change. So the collected labels are first used to train a separate model that imitates the judgments.
In reinforcement learning, a reward is a number that says how good an action or outcome was. A game has a score built in, while a written answer has none. A reward model is the learned judge that supplies one. It takes a prompt $x$ and a response $y$ and returns one number $r(x, y)$, an estimate of how much people would prefer that response. Higher usually means better.

A reward model is often built from an existing language model, commonly the SFT model. For a sequence of $T$ tokens and a vocabulary of $V$ tokens, a language model ends in a head that outputs a $T \times V$ grid of scores, one score per vocabulary token at each position. The reward model swaps that head for one that outputs a single number for the whole sequence. The rest of the network stays the same.

Each training batch holds every prompt twice, once followed by its chosen response and once by its rejected one. The reward model scores both sequences.
The Bradley-Terry loss
Two scores become a probability through the Bradley-Terry model, a common choice for this step. Write $y_w$ for the chosen response and $y_l$ for the rejected one. $\sigma$ is the sigmoid function $\sigma(z) = 1/(1+e^{-z})$, which turns any number into a value between 0 and 1. The model says:
$$P(\text{chosen over rejected})$$
$$= \sigma\big(r(x, y_w) - r(x, y_l)\big)$$
Only the difference between the two scores counts. For example, if the chosen answer scores 2.4 and the rejected one scores 1.1, the difference is 1.3 and $\sigma(1.3) \approx 0.79$. A difference of 0 gives 0.5, an even chance.

Training pushes this probability toward 1 for every labeled pair. The loss $L$ is the negative log of the probability:
$$L = -\log \sigma\big(r(x, y_w) - r(x, y_l)\big)$$
When the chosen response scores well above the rejected one, the probability is near 1 and the loss is near 0.
Here is one step by hand. Before training, a reward model might score the chosen answer 0.10 and the rejected answer 0.25. The margin, chosen minus rejected, is $0.10 - 0.25 = -0.15$. Then $\sigma(-0.15) \approx 0.46$, so the model gives the chosen answer slightly less than even odds. The loss is $-\log 0.46 \approx 0.77$, and gradient descent on it raises the chosen score, lowers the rejected score or does both.

In PyTorch the loss is one line. F.logsigmoid computes $\log \sigma$ in a numerically stable way. Training code often tracks accuracy too, the fraction of pairs where the chosen response scores higher.
1import torch
2import torch.nn.functional as F
3
4def reward_loss_and_acc(r_chosen, r_rejected):
5 loss = -F.logsigmoid(r_chosen - r_rejected).mean()
6 acc = (r_chosen > r_rejected).float().mean()
7 return loss, acc
8
9# before training: the rejected answer scores higher
10before = reward_loss_and_acc(torch.tensor([0.10]), torch.tensor([0.25]))
11# after training: the chosen answer scores higher
12after = reward_loss_and_acc(torch.tensor([1.40]), torch.tensor([-0.30]))
13# the same scores with 5 added to both
14shifted = reward_loss_and_acc(torch.tensor([6.40]), torch.tensor([4.70]))
15
16for name, (loss, acc) in [("before", before), ("after", after), ("shifted", shifted)]:
17 print(f"{name:8} loss={loss.item():.3f} acc={acc.item():.1f}")1before loss=0.771 acc=0.0
2after loss=0.168 acc=1.0
3shifted loss=0.168 acc=1.0After training, the same kind of pair might score 1.40 for chosen and -0.30 for rejected. That is a margin of 1.70 and a probability of about 0.85, and the loss drops to 0.168. In real training r_chosen and r_rejected come from the reward model, so loss.backward() and an optimizer step would then update its weights.
The shifted line adds 5 to both scores and the loss stays the same. Reward scores are relative. Only differences between responses carry meaning, so a score of 0 has no meaning on its own.

The reward model has learned a scoring pattern from the labels, which is different from learning what is true. It can inherit label noise, shortcuts and blind spots from its training data.
Once trained, it can score new outputs automatically. It can filter out low-scoring synthetic training data. It can also run best-of-N sampling at inference, when the model is used rather than trained: draw $N$ answers for a prompt, score them and return the top one. Best-of-N can improve the answers users see, and it inherits the reward model's blind spots too. The main use of the reward model is RLHF.

Where RLHF fits
A common pipeline for a chat model runs in order:
- Pretraining builds a base model from broad text.
- SFT turns that base model into an instruction-following model with written demonstrations.
- Preference data trains a reward model.
- RLHF starts from the SFT model and updates it using the reward model's scores.
RLHF comes after SFT and does not replace it. SFT gives the model its basic assistant behavior, and RLHF shifts that behavior toward answers people prefer.

The RLHF loop
RLHF changes the SFT model with reinforcement learning. In reinforcement learning terms the model being trained is the policy. It sees a prompt and generates a response, which is its action. The reward model scores that response, which gives the reward. The update then makes high-scoring responses more likely, and the loop repeats with the next prompt.

Several models take part, each with one job:
- Policy: the SFT model being updated.
- Reference model: a frozen copy of the SFT model, used to measure how far the policy has moved.
- Reward model: the learned judge, which scores each generated response.
- Value model: a helper that some reinforcement learning optimizers use to estimate how good a response is expected to be. It makes the update less noisy.
The reference and reward models usually stay fixed during this step. The policy is the only one of them that is the assistant being improved.

Reward hacking
The reward model is a proxy for human judgment, a learned estimate of it that can be wrong. A policy told to maximize the reward model's score with no other limit can find outputs that score high without being good. It may find that very long answers score well, or that a certain phrasing gets rewarded, and produce more of that instead of becoming more helpful. This is called reward hacking: raising the number instead of the quality the number was meant to measure.

The KL penalty
RLHF limits reward hacking by keeping the policy close to where it started. The frozen reference model is that starting point. The policy earns reward for better answers and pays a penalty when its probabilities move too far from the reference model's.
The distance is measured with KL divergence, a number that says how different two probability distributions are and that is 0 when they match. Here one distribution is the probabilities the policy gives to responses, written $\pi_\theta(y \mid x)$. The other is the probabilities the reference model gives, written $\pi_{\text{ref}}(y \mid x)$. $\mathbb{E}_{y \sim \pi_\theta}$ means an average over responses $y$ sampled from the policy. KL divergence is the average log-ratio of the two probabilities:
$$D_{KL}\big(\pi_\theta \,\|\, \pi_{\text{ref}}\big)$$
$$= \mathbb{E}_{y \sim \pi_\theta}\big[\log \pi_\theta(y \mid x)$$
$$- \log \pi_{\text{ref}}(y \mid x)\big]$$
RLHF samples one response at a time. For that single response, the bracket is the estimate it uses: the response's log-probability under the policy minus its log-probability under the reference.
For example, take the prompt "Explain dropout in two sentences." The policy samples "Dropout randomly hides some activations during training, which makes the network rely less on any single feature. This can improve generalization." Three numbers come from that response. The reward model scores it 1.0. Its log-probability is -5.0 under the policy and -6.0 under the reference.

The drift is $-5 - (-6) = 1$, so the policy made this response more likely than the reference did. With a penalty weight $\beta = 0.2$, the penalty is $0.2 \times 1 = 0.2$. The reward used for the update is $1.0 - 0.2 = 0.8$:
1rm_score = 1.0 # reward model's score for the sampled response
2policy_logprob = -5.0 # log-probability of the response under the model being trained
3ref_logprob = -6.0 # log-probability under the frozen reference copy
4beta = 0.2
5
6drift = policy_logprob - ref_logprob
7reward = rm_score - beta * drift
8print("drift:", drift)
9print("reward used for the update:", round(reward, 3))1drift: 1.0
2reward used for the update: 0.8The response still gets a positive reward, but less than its full score of 1.0. A larger $\beta$ would take more of it away.

The RLHF objective
The step is often written as one objective with these symbols:
- $x$: the prompt.
- $y$: a response sampled from the current model $\pi_\theta$.
- $r(x, y)$: the reward model's score for that response.
- $\pi_{\text{ref}}$: the frozen SFT reference.
- $\beta$: the strength of the penalty.
The objective is:
$$\max_{\pi_\theta} \; \mathbb{E}_{y \sim \pi_\theta}\big[r(x, y)\big]$$
$$- \beta \, D_{KL}\big(\pi_\theta \,\|\, \pi_{\text{ref}}\big)$$
In words, RLHF looks for the policy with the highest average reward, minus a penalty for moving away from the SFT model.

The penalty also guards against a second failure. Preference data covers a narrow part of what the model can do. A policy that chases reward on that narrow part with no limit can overwrite skills it learned in pretraining, which is called catastrophic forgetting. Staying close to the reference keeps the policy fluent while the reward shifts it toward preferred answers.

One RLHF step
One simplified RLHF step runs in this order:
- The policy generates a response to a prompt.
- The reward model scores the response.
- The policy and the reference model each give the response's log-probability.
- The reward for the update is the score minus $\beta$ times the difference of the two log-probabilities.
- A reinforcement learning update changes the policy so higher-reward responses become more likely.
A common optimizer for step 5 is PPO, short for proximal policy optimization. It is a reinforcement learning update rule that changes the policy in controlled steps. Only the policy's weights change during the step.

How RLHF differs from classic reinforcement learning
A game-playing agent often starts with little useful behavior and learns from a hard win-or-lose signal. In RLHF the policy is already pretrained and instruction-tuned, and it already writes coherent answers. Training mostly shifts its habits rather than building language ability from scratch. The reward is different too, since it comes from a learned reward model that can be wrong instead of from a real outcome.

Why RLHF is hard to run
During training RLHF may keep four models in memory: the policy, the frozen reference, the reward model and the value model. That takes a lot of memory. The reinforcement learning loop can also be sensitive to hyperparameters, and training can become unstable if the KL weight $\beta$ or the learning rate is off. This cost led to simpler preference methods such as DPO, which DPO vs RLHF compares side by side.

When to use RLHF and common mistakes
RLHF fits after SFT, once the model already follows instructions and the goal is to move its answers toward the ones people prefer. It is not a second pretraining run, and it is not where a model first learns to follow instructions.
Mistakes that come up:
- Treating the reward score as a measure of truth. It is a pattern learned from labels, with their noise and blind spots.
- Setting $\beta$ too low or dropping the KL penalty. The policy can then find reward hacks and forget skills from pretraining.
- Reading a reward model's score as meaningful on its own. Only the difference between two responses to the same prompt carries information.
- Starting RLHF from a base model that skipped SFT. RLHF shifts a model that already follows instructions, and the reference it measures drift against is that SFT model.
Related concepts
RLHF is the third stage of the path described in pretraining vs post-training, and it starts from the model built in instruction tuning and SFT. DPO vs RLHF covers the method that trains on the same preference pairs without a reward model. KL divergence is explained from the start in entropy, cross-entropy and KL divergence. How to tell whether RLHF helped, and where it still falls short, is in how LLM alignment is evaluated.
QuiddityML teaches preference learning and RLHF as two concepts in the Intro to NLP track, where the exercises include filling in the Bradley-Terry loss, finding the bug in a reward loss and putting the steps of one RLHF update in order.