Preference optimisation: RLHF, DPO and friends

How human or AI preferences shape a model: reward models, PPO, and the simpler DPO objective with code.

Expert about 6 h

The picture

  1. 01

    Prompts

    diverse

  2. 02

    Two answers

    chosen vs rejected

  3. 03

    Preference data

    pairs

  4. 04

    DPO loss

    vs reference model

  5. 05

    Evaluate

    win rate + regressions

Why preferences

Demonstrations (SFT) teach what a good answer looks like, but it is often easier to say which of two answers is better than to write a perfect one. Preference learning uses those comparisons to push the model towards what people (or a trusted AI judge) prefer: helpfulness, honesty, safety, concision.

The classic pipeline (RLHF)

  1. SFT a base model.
  2. Collect comparisons: for a prompt, two samples, a label for which is better.
  3. Train a reward model to score responses so that preferred ones score higher (Bradley-Terry model).
  4. Optimise the policy with PPO to maximise reward while a KL penalty keeps it close to the SFT model.

It works, but it is complex: four models in memory, unstable training, many hyper-parameters.

DPO: skip the reward model

DPO shows that the optimal policy under the KL-regularised objective has a closed form, so you can train on preference pairs directly with a classification-style loss. For a prompt xx with chosen answer ywy_w and rejected yly_l:

LDPO=−log⁡σ ⁣(β[log⁡πθ(yw∣x)πref(yw∣x)−log⁡πθ(yl∣x)πref(yl∣x)])\mathcal{L}_{DPO} = -\log \sigma\!\Big(\beta\big[\log\tfrac{\pi_\theta(y_w|x)}{\pi_{ref}(y_w|x)} - \log\tfrac{\pi_\theta(y_l|x)}{\pi_{ref}(y_l|x)}\big]\Big)

The policy πθ\pi_\theta is rewarded for raising the likelihood of the chosen answer relative to the reference model more than it raises the rejected one. β\beta controls how far it may move from the reference.

import torch, torch.nn.functional as F

def seq_logp(model, input_ids, attention_mask, prompt_lens):
    logits = model(input_ids=input_ids, attention_mask=attention_mask).logits[:, :-1]
    labels = input_ids[:, 1:]
    logp = torch.gather(F.log_softmax(logits.float(), -1), 2, labels.unsqueeze(-1)).squeeze(-1)
    mask = attention_mask[:, 1:].clone()
    for i, n in enumerate(prompt_lens):
        mask[i, : n - 1] = 0                      # count only response tokens
    return (logp * mask).sum(-1)

def dpo_loss(policy, ref, chosen, rejected, prompt_lens, beta=0.1):
    pc = seq_logp(policy, **chosen, prompt_lens=prompt_lens)
    pr = seq_logp(policy, **rejected, prompt_lens=prompt_lens)
    with torch.no_grad():
        rc = seq_logp(ref, **chosen, prompt_lens=prompt_lens)
        rr = seq_logp(ref, **rejected, prompt_lens=prompt_lens)
    margin = beta * ((pc - rc) - (pr - rr))
    return -F.logsigmoid(margin).mean(), (margin > 0).float().mean()      # loss, preference accuracy

With TRL

from datasets import load_dataset
from trl import DPOTrainer, DPOConfig

# each row: {"prompt": ..., "chosen": ..., "rejected": ...}
ds = load_dataset("json", data_files="prefs.jsonl", split="train")
args = DPOConfig(output_dir="out/dpo", beta=0.1, learning_rate=5e-7, per_device_train_batch_size=2,
                 gradient_accumulation_steps=16, num_train_epochs=1, bf16=True, logging_steps=10)
trainer = DPOTrainer(model=model, args=args, train_dataset=ds, processing_class=tok)   # reference model handled for you
trainer.train()

Run DPO after SFT, with a much smaller learning rate than SFT (around 5e-7 for full fine-tuning; higher for LoRA).

Where preferences come from

  • Human annotators: highest quality, slowest, expensive.
  • AI feedback (RLAIF, Constitutional AI): a model judges pairs against written principles. Cheap and scalable; inherits the judge's biases.
  • On-policy sampling: generate several answers from your current model and rank them, which usually works better than reusing off-policy pairs.
  • Verifiable signals: tests, exact match, rules (see the next topic).

What goes wrong

  • Length bias: judges and annotators prefer longer answers, so the model learns to ramble. Control for length in your pairs and evaluation.
  • Reward hacking and over-optimisation: the model exploits quirks of the signal. Keep β\beta meaningful, stop early, and evaluate on independent measures.
  • Noisy labels cap what you can learn. Audit a sample by hand.
  • Likelihood displacement: both chosen and rejected likelihoods can drop. Watch absolute log-probs, not only the margin.
  • Alignment tax: capabilities slip. Run regression benchmarks.

Alternatives such as KTO (needs only good/bad labels, not pairs) and ORPO (no reference model) trade simplicity against stability. Evaluate rather than assume.

Common mistakes

  • Running DPO on a base model with no SFT.
  • Learning rate copied from SFT.
  • Judging success by preference accuracy on the training pairs.

Exercises

  1. Build 500 preference pairs for a style you care about, run DPO, and measure win rate against the SFT model with a held-out judge and a human spot check.
  2. Show the effect of beta at 0.05, 0.1 and 0.5 on output length and win rate.

You are done when you can…

  • Write the DPO loss from the preference model and implement it in PyTorch
  • Explain what beta controls and what happens if it is too small or too large
  • Build a preference dataset and detect when it is teaching the wrong thing