🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

RLHF: Aligning Models With Human Preferences

đŸŸĸ Free Lesson

RLHF: Aligning Models With Human Preferences

Supervised tuning can show a model what a good answer looks like, but it cannot express preferences between two good answers — which is more honest, less verbose, better aimed at a beginner. Reinforcement learning from human feedback closes that gap by learning a scoring function from comparisons and then optimizing against it. The result is the difference between a model that has seen examples of helpfulness and one that reliably reaches for it. This lesson walks the three stages, the loss functions that make them work, and the traps that make runs expensive.

The Gap Between Imitation and Preference

Cross-entropy training on demonstrations has an uncomfortable property: it treats every token of a response as equally correct, even when the response is merely acceptable. Human judgment is comparative — people are far more reliable at saying which of two answers they prefer than at authoring a perfect answer from scratch. RLHF converts that comparative signal into a scalar the model can climb.

The pipeline has three stages. Supervised fine-tuning establishes a competent starting policy. A reward model is trained to reproduce human rankings of model outputs. Then the policy is optimized against that reward with a reinforcement learning algorithm, while a KL penalty keeps it near the supervised model. That penalty is not a detail: without it the policy discovers degenerate outputs that the reward model scores highly, and quality collapses within a few hundred steps.

Preferences Worth Collecting

Preference data quality dominates everything downstream. Guidelines must define what is being ranked — helpfulness, harmlessness, honesty — with concrete instructions rather than vibes, because annotator disagreement is otherwise unmeasurable. Sample responses from the policy you actually intend to improve, at varying quality, so the reward model learns the boundary near where it will be used rather than on obvious mismatches.

Pitfall in collectionSymptom laterMitigation
Annotators rank on length aloneReward grows with verbosityLength normalization, explicit brevity guidance
Ties and near-ties labeled arbitrarilyNoisy reward, unstable trainingAllow ties; filter low-agreement pairs
Only one prompt templateReward overfits phrasingDiverse, realistic prompt sources
Responses from an older policyReward misjudges new styleRefresh samples each collection round
No rubric calibrationHigh inter-annotator varianceTraining rounds, spot audits, agreement metrics
Single rater per pairIndividual bias baked inMultiple raters, majority or averaged preference

Measure pairwise agreement as you go. If two trained annotators agree barely more than chance on your task, no algorithm downstream will rescue the signal.

Fitting a Reward Model

The reward model is a supervised model with a scalar head: score a prompt-response pair, and train so that the chosen response outscores the rejected one. The standard loss is the negative log-sigmoid of the score difference, a pairwise logistic objective that only cares about ordering — which matches how the data was collected. At inference the reward model is just a function returning a float, so it can also be used offline to filter candidates or rank beams.

python
import torch
import torch.nn as nn
import torch.nn.functional as F

class RewardModel(nn.Module):
    def __init__(self, base):
        super().__init__()
        self.base = base
        hidden = base.config.hidden_size
        self.head = nn.Linear(hidden, 1)
        nn.init.zeros_(self.head.bias)
        nn.init.normal_(self.head.weight, std=0.01)

    def score(self, input_ids, attention_mask):
        out = self.base(input_ids=input_ids, attention_mask=attention_mask)
        last = out.last_hidden_state[:, -1, :]
        return self.head(last).squeeze(-1)

    def forward(self, chosen_ids, chosen_mask, rejected_ids, rejected_mask):
        chosen = self.score(chosen_ids, chosen_mask)
        rejected = self.score(rejected_ids, rejected_mask)
        return -F.logsigmoid(chosen - rejected).mean()

model = RewardModel(load_backbone("gpt2"))
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-5)

for batch in preference_batches:
    loss = model(batch["chosen_ids"], batch["chosen_mask"],
                 batch["rejected_ids"], batch["rejected_mask"])
    loss.backward()
    torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
    optimizer.step()
    optimizer.zero_grad()

Watch for reward model overfitting: if it drives training loss to zero while held-out agreement stalls, the reward will be exploitable. Keep a held-out pair set and stop based on it.

Optimizing the Policy With PPO

Proximal policy optimization treats the reward model as the environment: sample a response, score it, and update the policy to increase that score while staying within a trust region of the previous policy. Three terms shape each update — the policy gradient from the reward, a value function's advantage estimate, and the KL penalty against the reference policy. The KL coefficient is the knob you tune most: too low and the model drifts into reward-hacking loops, too high and training does nothing.

python
from trl import PPOConfig, PPOTrainer, AutoModelForCausalLMWithValueHead
from transformers import AutoTokenizer

def make_trainer(base_name):
    config = PPOConfig(
        model_name=base_name,
        learning_rate=1.4e-5,
        batch_size=32,
        mini_batch_size=8,
        ppo_epochs=4,
        kl_penalty="kl",
        init_kl_coef=0.15,
        target_kl=6.0,
        cliprange=0.2,
    )
    model = AutoModelForCausalLMWithValueHead.from_pretrained(base_name)
    tok = AutoTokenizer.from_pretrained(base_name)
    tok.pad_token = tok.eos_token
    return PPOTrainer(config=config, model=model, tokenizer=tok), tok

def run_step(trainer, prompts, reward_fn):
    query_tensors = [trainer.tokenizer.encode(p, return_tensors="pt")[0] for p in prompts]
    response_tensors = trainer.generate(query_tensors, max_new_tokens=128)
    rewards = [reward_fn(p, trainer.tokenizer.decode(r)) for p, r in zip(prompts, response_tensors)]
    stats = trainer.step(query_tensors, response_tensors, rewards)
    return stats

trainer, tok = make_trainer("gpt2")
print("PPO ready; watch kl and reward per step for divergence")

Two health signals matter more than the headline reward: the KL to the reference policy, which should stabilize rather than climb without bound, and reward variance, which should shrink as the policy converges. A reward line that rises while KL explodes means the model has found a shortcut rather than an improvement.

DPO and the Alternatives

Direct preference optimization removes the reward model entirely by rewriting the objective: the policy is trained directly on preference pairs, pushing chosen responses up and rejected ones down relative to a frozen reference, with the same KL anchor expressed inside the loss. It needs no reinforcement learning loop, no value network, and far fewer hyperparameters, which makes it the default for teams without an RL background. The trade-off is that you lose the reusable scalar reward — handy for offline filtering — and the ability to interleave other reward sources such as a safety classifier.

Other options fill specific niches. Reinforcement learning from AI feedback substitutes model-generated judgments for human ones, cutting cost at the price of inheriting model biases. Reward-model-free methods that optimize directly on a judge's score are simple but vulnerable to judge gaming. Best-of-n sampling avoids training entirely by generating several candidates and selecting with a reward model, paying inference cost instead of training cost — often the right answer when traffic is modest.

ApproachTrains a reward modelRL loopExtra inference costBest when
PPO with RMYesYesLowYou have RL expertise and scale
DPONoNoNoneFast iteration, small teams
RLAIFAI preference labelsOptionalMediumHuman labeling is the bottleneck
Best-of-nOptionalNoHigh per queryLow volume, no training budget
Rejection sampling then SFTNoNoOne offline passYou only need the best candidates

Reward Hacking and How to Spot It

Reward hacking is the model optimizing the proxy instead of the goal: it discovers that confident hedging, bullet lists, or specific phrasing earns high reward scores and repeats them regardless of content. Warning signs include length drift, collapsing diversity across samples, and a reward curve that keeps climbing while human spot checks say quality is flat. The defenses are structural — length normalization in scoring, holdout preference evaluations, periodic human audits — and procedural: keep the KL coefficient nonzero and monitor it.

A second failure is over-optimization to a narrow preference set. If your prompts came from a single team, the aligned model learns that team's tastes. Widen prompt sources, rotate them, and re-evaluate on traffic from other segments after every run.

â„šī¸Where to start

Unless you have a specific reason for PPO, start with rejection sampling plus supervised fine-tuning, then DPO. They cover most preference-tuning goals with a fraction of the moving parts.

Common Mistakes

Skipping the KL anchor to speed up learning

Fix: Keep a reference policy and a nonzero KL coefficient; without them collapse is fast and ugly

Training a reward model on obvious quality gaps

Fix: Sample from the current policy so the reward learns the boundary it will be judged on

Reading reward curves as quality

Fix: Pair every run with held-out preference checks and human spot audits

Ignoring length bias in preferences

Fix: Normalize for length or instruct raters explicitly, then monitor output length over training

Jumping to RL before exhausting simpler options

Fix: Try rejection sampling and DPO first; add PPO only when they plateau

Key Takeaways

  • RLHF converts comparative human judgments into a scalar the policy can optimize
  • Annotation quality and agreement metrics decide more than the RL algorithm does
  • The reward model is a pairwise ranking model trained with a logistic objective
  • PPO needs a KL anchor against a reference policy to avoid reward hacking
  • DPO and rejection sampling reach most of the goal with far fewer moving parts
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Generative AI Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement