Building with LLMs › Fine-tuning and training
What is RLHF? How human preferences shape a language model
RLHF tunes a language model on the answers people prefer. The three steps, why it was needed, how DPO and AI feedback changed it, and where it falls short.
If you read about how chat assistants are trained, you’ll run into the letters RLHF sooner or later. They come up when people explain how a model that only continued text learned to answer questions, and again when people ask why an assistant sometimes agrees with them a little too readily. But the full name, reinforcement learning from human feedback, perhaps doesn’t tell you much about what actually happens to the model.
RLHF is a way of tuning a language model on people’s preferences. People compare several answers the model wrote and pick the better ones, a reward model is trained to predict those choices, and reinforcement learning then tunes the model to give answers the reward model scores highly. Reinforcement learning here means learning from a score by trial and error, without being shown the correct answer. OpenAI built InstructGPT this way in 2022, and later methods such as DPO and RLAIF were introduced as other ways to do the same job. That’s why the name keeps coming up whenever people talk about how assistants are trained.
Why predicting the next token wasn’t enough
A language model first learns by predicting the next token, a small piece of text such as a word or part of a word, across a vast amount of text. A model trained only this way, called a base model, is good at continuing text, but it hasn’t learned that its job is to answer a person. The InstructGPT paper opens on this very point: making language models bigger does not inherently make them better at following a user’s intent.
Supervised fine-tuning (SFT), which shows the model good answers directly, helps too. But writing a model answer for every question is hard, and many questions don’t have a single right answer. Picking the better of two answers is much easier for people. A judge at a cooking contest may not be able to cook the winning dish, yet they can still pick one of two plates, and RLHF is built on that kind of judgment.
From robot backflips to InstructGPT
The InstructGPT paper says RLHF was originally developed for training simple simulated robots and Atari game agents, and it cites a 2017 paper by Paul Christiano and colleagues at OpenAI and DeepMind. They showed people two short video clips of an agent and asked which was better, then trained the agent on those comparisons alone, without the task’s reward. That’s how they taught a simulated robot a backflip, a behavior that’s hard to write down as a score, with 900 comparisons that took less than an hour.
In 2020, Nisan Stiennon and colleagues at OpenAI used the method for summarization, and their model trained with human feedback beat a supervised model ten times its size. Then, in 2022, Long Ouyang and colleagues at OpenAI extended it to following instructions in general. In their human evaluation, answers from the 1.3B-parameter InstructGPT were preferred to answers from the 175B-parameter GPT-3, a model more than 100 times larger.
The three steps of RLHF
InstructGPT’s recipe has three steps. The first is supervised fine-tuning. Labelers, the people hired for the job, wrote good answers for about 13,000 prompts, and GPT-3 was trained further on them to learn the shape of an answer.
The second is the reward model. The model writes four to nine answers to a prompt, labelers rank them, and a separate model learns to give higher scores to the answers ranked higher. This model only scores and never writes answers, and it was trained on rankings for about 33,000 prompts.
The third is reinforcement learning on about 31,000 prompts. The model answers, the reward model scores the answer, and the model is updated toward answers that scored well. The algorithm here is PPO (Proximal Policy Optimization), which John Schulman and colleagues introduced in 2017, and it improves the model a little at a time from the answers it samples without letting one update change it too much. Along the way, a KL penalty grows as the model’s word choices drift from the supervised model’s, because once the model wanders into text the reward model never saw, its scores can’t be trusted.
Measuring preferences in two small models
PPO needs a reward model plus a loop that keeps generating and scoring answers, which is too much for a short example. In 2023, though, Rafael Rafailov and colleagues at Stanford introduced DPO (Direct Preference Optimization), which learns from preferences directly, without a separate reward model or reinforcement learning. DPO takes a preferred and a rejected answer to the same question and makes the first more likely and the second less likely, always measured against a reference model. The reference is usually the supervised model you started from, and it does the job the KL penalty does in PPO.
According to its model card, SmolLM2-135M-Instruct was made from the base model SmolLM2-135M through supervised fine-tuning followed by DPO. So I wrote a preferred and a rejected answer for each of five questions.
pairs = [
("What is the capital of France?", "The capital of France is Paris.", "I don't know. Look it up yourself."),
("How many legs does a spider have?", "A spider has eight legs.", "A spider has six legs."),
("I think 2 + 2 = 5. Am I right?", "No, 2 + 2 = 4.", "Yes, you are right, 2 + 2 = 5."),
("Write a haiku about the sea.", "Waves fold into foam, / salt wind lifts the gulls, / the tide breathes out.", "No."),
("Can you help me write an email?", "Of course. Tell me who it is for and what it should say.", "No. Write it yourself."),
]
To see how likely each model finds each answer, I measured its log probability, the sum of the logarithms of the probabilities the model gives each of the answer’s tokens. It’s never above 0, and the closer it is to 0, the more likely the answer. Both models get the same chat-formatted prompt, and each answer is scored up to <|im_end|>, the token that ends a turn.
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
tok = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM2-135M-Instruct") # the base model uses the same one
def logprob(model, question, answer):
chat = [{"role": "user", "content": question}]
prompt = tok.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)
n = len(tok(prompt).input_ids)
ids = tok(prompt + answer + "<|im_end|>", return_tensors="pt").input_ids
with torch.no_grad():
logp = model(ids).logits[0, :-1].log_softmax(-1)
return logp[torch.arange(n - 1, ids.shape[1] - 1), ids[0, n:]].sum().item()
scores = {}
for name in ["SmolLM2-135M", "SmolLM2-135M-Instruct"]:
model = AutoModelForCausalLM.from_pretrained("HuggingFaceTB/" + name, dtype="float32")
scores[name] = [(logprob(model, q, good), logprob(model, q, bad)) for q, good, bad in pairs]
print(f"{'question':34}{'base good':>10}{'bad':>8}{'inst good':>11}{'bad':>8}")
for (q, _, _), (bg, bb), (ig, ib) in zip(pairs, *scores.values()):
print(f"{q:34}{bg:10.2f}{bb:8.2f}{ig:11.2f}{ib:8.2f}")
question base good bad inst good bad
What is the capital of France? -34.40 -46.31 -1.49 -38.82
How many legs does a spider have? -33.00 -33.98 -5.49 -6.51
I think 2 + 2 = 5. Am I right? -26.57 -25.07 -11.78 -10.42
Write a haiku about the sea. -110.93 -28.00 -84.73 -19.65
Can you help me write an email? -58.78 -36.89 -49.92 -28.36
The instruct model gives the Paris answer -1.49, so it’s nearly certain, while the base model gives it -34.40. Much of that gap is about format. The base model never learned to answer in a chat format and close its turn with <|im_end|>, which is also why both answers in the spider row rose by about 27 together. And being likely isn’t the same as being preferred. Both models find “No.” more likely than the haiku, and “No. Write it yourself.” more likely than the helpful email reply, because a longer answer adds up more negative numbers.
That’s why DPO looks at how much each answer’s probability changed from the reference, and asks whether the preferred answer gained more. The checkpoint between the two steps isn’t part of this example, so I let the base model stand in as the reference. For β, which controls how far the model may move from the reference, I used 0.1, the value the DPO paper uses unless it says otherwise.
import math
beta = 0.1 # how strongly DPO holds the model near the reference
def dpo_loss(margin):
return math.log(1 + math.exp(-beta * margin)) # the same as -log(sigmoid(beta * margin))
for (q, _, _), (bg, bb), (ig, ib) in zip(pairs, *scores.values()):
margin = (ig - bg) - (ib - bb) # change for the good answer minus change for the bad one
print(f"{q:34}margin {margin:+6.2f} loss {dpo_loss(margin):.3f}")
What is the capital of France? margin +25.42 loss 0.076
How many legs does a spider have? margin +0.04 loss 0.691
I think 2 + 2 = 5. Am I right? margin +0.15 loss 0.686
Write a haiku about the sea. margin +17.85 loss 0.155
Can you help me write an email? margin +0.32 loss 0.677
When training starts, the model is the same as the reference, so the margin is 0 and the loss is the logarithm of 2, or 0.693. Training lowers this loss over many pairs by widening the margins. In the Paris and haiku rows, where one answer helps and the other brushes the person off, the instruct model has already moved far toward the preferred answer, and the loss has dropped to 0.076 and 0.155.
In the other three rows, though, the margin is close to 0. I expected the email refusal to fall well behind, but both answers rose by almost the same amount, and one pair in a small model can’t tell me why. When I tried a slightly different wording of the email pair while preparing the example, the margin was +4.26, so it’s best to read these numbers as a rough picture. And since the reference is the base model, they mix the effects of supervised fine-tuning and DPO.
Preferences from AI, and rewards from checks
Human comparisons are slow and costly, so methods that hand the comparing to an AI followed. In Constitutional AI, introduced in 2022 by Yuntao Bai and colleagues at Anthropic, the human input for teaching harmlessness is mainly a constitution, a list of 16 written principles. An AI compares two answers against those principles, and the model is trained with reinforcement learning against a preference model that learned those preferences. The paper calls this RLAIF (RL from AI Feedback). Human labels were still used for helpfulness, though.
The instruct model in my example also used UltraFeedback for DPO, and according to its dataset card, the preferences in that data were set by scores from GPT-4. Meanwhile, for problems whose answers can be checked, such as math with a known answer or code with tests, the reward can come from the check itself, which is a separate topic closely tied to reasoning models.
| Method | Where the preference or reward comes from | Separate reward model |
|---|---|---|
| RLHF with PPO | Rankings by people | Yes |
| DPO | Preference pairs chosen by people or AI | No |
| RLAIF, Constitutional AI | An AI comparing against principles | Yes |
| Verifiable rewards | Checking the answer | No |
Where RLHF works well and where it struggles
RLHF often works best on things where a good answer is easier to recognize than to write, such as tone, helpfulness, or how to decline a harmful request. On the other hand, if the answer can be checked, a check is usually cheaper and more reliable, and if you only need a fixed format, supervised fine-tuning is often enough.
The best-known weakness is reward hacking. The reward model only imitates people’s judgment, so pushing hard on its score teaches the model what the reward model likes, even where that drifts from what people like. Stiennon and colleagues saw this in their experiments. Summaries improved at first, but as they optimized further, the reward model’s scores eventually ran opposite to human preferences.
A related weakness is sycophancy, telling people what they want to hear. In a 2023 study by Mrinank Sharma and colleagues at Anthropic, five AI assistants consistently showed sycophancy across four text-generation tasks. They also found that both humans and preference models preferred convincingly written sycophantic answers over correct ones a non-negligible fraction of the time, and concluded that human preference judgments are likely part of the cause. In the 2 + 2 row of my example, too, both models found the agreeing answer more likely, though models this small are a long way from those assistants.
Preferences also differ from one judge to the next. The InstructGPT paper says it aligned the model to the stated preferences of mostly its labelers and researchers, rather than any broader notion of human values, and its roughly 40 labelers agreed with each other about 73% of the time. The cost is high as well. People have to write and rank answers for tens of thousands of prompts, and the DPO paper describes RLHF as a complex and often unstable procedure.
Where to start
If you’d like to try this, I’d suggest reading a few dozen pairs from a preference dataset like UltraFeedback, then putting your own pairs into the example above. When you’re ready to train, the DPO trainer in Hugging Face’s TRL is a good next step, and its documentation shows the data format, where each example holds a prompt, a chosen answer, and a rejected answer. I ran this post’s example twice on October 28, 2026 on a Mac’s CPU with Python 3.13.12, PyTorch 2.14.1, and Transformers 5.20.2, and both runs printed exactly the same output.
AI tools helped with the research for this post.