LLMModule 08 · Stage 05

Advanced alignment & preference optimisation

Module 07 showed why preference data works and how DPO falls out of the KL-regularised objective. This stage goes past DPO: KTO learns from plain thumbs-up/thumbs-down labels, ORPO folds alignment into SFT, reward models get trained properly, and reward hacking gets measured and fought instead of just noticed.

PrerequisitesSFT, log-probabilities, Module 07's DPO and KL leash, basic PyTorch
Time2–3 weeks part-time (about 25–40 h)
HardwareColab GPU for a 0.5B model with LoRA · one 80 GB GPU for the 7B version
Key papersDPO (Rafailov et al., 2023) · KTO (Ethayarajh et al., 2024) · ORPO (Hong et al., 2024) · Reward over-optimisation (Gao et al., 2022)

Source: Suraj Sharma, X post (stage 5) · roadmap hub: Module 08

Start here (no maths needed)

After a chatbot learns to talk, we teach it manners by showing it which of its own answers people liked and which they didn't.

Think of it like this

Imagine you're learning to cook for your family. First you copy recipes from a book. That's like the first stage of training. Then, every night, your family says "yum" or "yuck" about dinner. They don't tell you how to fix it. They just give a thumbs up or down. Over weeks, you cook the "yum" dishes more and the "yuck" dishes less. But you still keep the basic cooking skills from the recipe book. And if you notice your little brother says "yum" to anything with extra sugar, you'd better not just pour sugar on everything. That trick is called "reward hacking".

How it works

  1. Start with a model that already answers questions (it learned from examples).
  2. Let it write several answers to many questions.
  3. People (or a careful checking program) mark answers as good or bad, or say which of two is better.
  4. Nudge the model so good answers become more likely and bad ones less likely, but only a little, so it doesn't forget what it knew.
  5. Check that it really got better, not just better at fooling the judge.

Why robots care

A robot that tidies a room can be judged the same way. A person watches two tries and says which was better, or just says "good job" or "not like that". The robot can learn from those simple signals. It's much easier than writing down exactly how to fold every shirt.

Try it

Words to know

Preference
A judgement that one answer is better than another.
Reward model
A program trained to guess how much people would like an answer.
Reference model
A frozen copy of the model from before this training, used to stop it drifting too far.
Reward hacking
Getting a high score by exploiting a flaw in the judge, not by actually doing better.
Binary feedback
A simple good/bad label, like a thumbs up or down.

Going deeper: everything below is the full version, with some maths. On a first read, skim the headings and the "Why it matters for robotics" box, and come back for the rest later.

1. What this stage covers

TL;DR

Preference optimisation reshapes an SFT model's output distribution toward answers people prefer, while a KL term keeps it near the SFT model. DPO does this from paired comparisons with a simple classification loss. KTO needs only unpaired good/bad labels, which are cheaper and more common in real products. ORPO removes the reference model and the separate alignment phase by adding an odds-ratio penalty to the SFT loss. If you keep an explicit reward model (for RLHF, best-of-n or data filtering), you train it with a Bradley–Terry loss, and you must expect over-optimisation: the proxy score keeps rising while true quality peaks and falls.

2. Concepts, explained

DPO, in one line, and what it leaves open

Module 07 derives DPO. The loss you implement is:

h(x, y_w, y_l) = log π_θ(y_w|x)/π_ref(y_w|x)  −  log π_θ(y_l|x)/π_ref(y_l|x)
L_DPO = −log σ( β · h )

The quantity β·log πθ/πref acts as an implicit reward. That's the "your language model is secretly a reward model" in the title of Rafailov, Sharma, Mitchell, Ermon, Manning and Finn (2023). Three practical gaps motivate the rest of this stage:

KTO: learning from good/bad labels

Ethayarajh, Xu, Muennighoff, Jurafsky and Kiela (2024) borrow from Kahneman and Tversky's prospect theory: people judge outcomes relative to a reference point, and losses hurt more than equal gains please. They show that DPO and similar losses already behave like "human-aware losses". KTO then maximises a prospect-theory-style utility of each output directly, so each training example is just (prompt, completion, good or bad).

r(x, y)  = log π_θ(y|x) / π_ref(y|x)           # implicit reward
z0       = estimate of KL(π_θ ‖ π_ref)          # reference point, no gradient
v(x, y)  = λ_D · σ( β·(r − z0) )   if y is desirable
         = λ_U · σ( β·(z0 − r) )   if y is undesirable
L_KTO    = E[ λ_y − v(x, y) ]

ORPO: alignment inside SFT

Hong, Lee and Thorne (2024) observe that SFT alone raises the probability of the rejected style too, because it's similar text. Their fix adds a small penalty during SFT itself, with no reference model and no second phase:

P(y|x)    = exp( mean token log-prob of y )      # length-normalised
odds(y|x) = P / (1 − P)
L_OR      = −log σ( log odds(y_w|x) − log odds(y_l|x) )
L_ORPO    = L_SFT(y_w)  +  λ · L_OR

Pros: one training run, one model in memory, roughly SFT cost. Cons: there is no explicit KL leash to the starting model, so the SFT term is what keeps the model grounded. You need paired data, and the chosen answers must be good enough to imitate. The paper reports gains for Phi-2, Llama-2 7B and Mistral 7B fine-tuned on UltraFeedback alone.

Reward modelling

A reward model is usually the SFT model with its language-model head swapped for a scalar head. It's trained on comparisons with the Bradley–Terry loss (the same one in Day 30):

L_RM = −log σ( r_φ(x, y_w) − r_φ(x, y_l) )

Reward hacking and how to fight it

Module 07's demo shows the shape. The measurements come from Gao, Schulman and Hilton (2022). They used a large "gold" reward model as stand-in humans, trained smaller proxy reward models on its labels, and optimised against the proxy. Gold score rose, peaked and fell as the policy moved away from the start (measured as d = √KL). The curve's shape differed between best-of-n and RL, and its coefficients changed smoothly with reward-model size. Mitigations that have evidence behind them:

Interactive: how hard does each loss push?

x-axis: the margin. For DPO it's h, the chosen-minus-rejected log-ratio. For KTO it's r − z0. Left: DPO loss. Right: KTO loss for a desirable and an undesirable example. The dot is the margin you pick. "Push" is the size of the loss gradient with respect to the margin.

DPO loss
–
DPO push
–
KTO push, good
–
KTO push, bad
–

Try this: at β = 0.1 and margin −30, DPO still pushes at about 0.095, close to its maximum of β. KTO's push on that desirable example is about 0.0045, roughly 20× smaller: it has mostly given up on it. KTO pushes hardest at margin 0, where the push is λ·β/4. That's the robustness-to-noise trade-off in one picture.

3. The practice project

(a) The Colab-sized version

The trick is to pick a behaviour a program can label, so you don't need human raters and you can measure the shift exactly.

  1. Model: a small instruction-tuned model (around 0.5B parameters, such as a Qwen2.5 or SmolLM2 instruct checkpoint). Train LoRA adapters only.
  2. Behaviour: choose something checkable, for example "when asked for JSON, return valid JSON with the requested keys and nothing else", or "answer in at most 80 words".
  3. Data: write or collect 300–1,000 prompts. Hold out 20% for evaluation. Sample 4 completions per training prompt at temperature 0.8–1.0 from the SFT model. Label each with your checker. You now have unpaired good/bad data, naturally imbalanced.
  4. Train KTO with Hugging Face TRL's KTOTrainer (dataset columns prompt, completion, label). Start at β = 0.1. Set the desirable and undesirable weights from your class counts. Check the current TRL docs, as argument names move between versions.
  5. Measure the shift on the held-out prompts, sampling several completions each: checker pass rate before and after, length distribution, distinct-n diversity, and the mean sampled log-ratio log πθ/πref (a KL estimate). Add a capability canary: 100–200 questions from a general benchmark the behaviour shouldn't touch.
  6. Ablate: sweep β, drop the undesirable examples, and compare against DPO trained on pairs built from the same samples (one passing and one failing completion per prompt).
from datasets import Dataset
from trl import KTOConfig, KTOTrainer
from peft import LoraConfig

rows = [{"prompt": p, "completion": c, "label": check(p, c)}
        for p in train_prompts for c in sample(model, p, n=4)]
n_good = sum(r["label"] for r in rows)
n_bad = len(rows) - n_good

cfg = KTOConfig(
    output_dir="kto-out", beta=0.1,
    desirable_weight=1.0,
    undesirable_weight=n_good / n_bad,   # keep the ratio near 1–4/3
    per_device_train_batch_size=8,       # z0 needs mismatched pairs in-batch
    learning_rate=5e-6, num_train_epochs=1,
)
trainer = KTOTrainer(model=model, args=cfg,
                     train_dataset=Dataset.from_list(rows),
                     processing_class=tok,
                     peft_config=LoraConfig(r=16, target_modules="all-linear"))
trainer.train()

What to expect: the pass rate should move if your checker is reasonable and the base model sometimes succeeds. If it starts near 0% or near 100%, there's little signal to learn from, so change the task. Don't trust any single run; use at least two seeds.

(b) The full version from the post

Take a 7B SFT model and align it with KTO on a real binary-feedback dataset (product thumbs data, or a pairwise dataset split into separate good and bad rows). Measure the behaviour shift with a held-out LLM judge plus human spot checks, alongside the measures above.

(c) Pitfalls

4. Reality check

The post's claim: SFT teaches a model what to say, alignment teaches it how to behave, without millions in annotation.

5. In this course

6. Why it matters for robotics

7. Self-check

Your product logs 50,000 thumbs-up and 5,000 thumbs-down responses. Which method fits, and how do you set its weights?

KTO, since the data is unpaired. With λD = 1, set λU so that λD·nD / (λU·nU) lands between about 1 and 4/3. Here 50,000 / (λU·5,000) ≤ 4/3 gives λU of roughly 7.5 to 10.

Why does KTO tolerate noisy labels better than DPO?

Its value function is a sigmoid of the margin, so the gradient vanishes when the model strongly disagrees with a label. A mislabelled example therefore has little pull. DPO's gradient approaches β on the wrong side and keeps pushing.

What does ORPO give up by dropping the reference model?

An explicit KL leash. Only the SFT term on the chosen answers keeps the model grounded, so poor chosen answers or a large λ can push it somewhere strange.

Your reward model has 72% held-out pairwise accuracy but prefers the longer answer 90% of the time. What do you do?

Treat length as a likely shortcut. Check accuracy on pairs of matched length, add length-balanced pairs or a length penalty, and report length next to every downstream win rate.

In Gao et al.'s setup, what is the x-axis of the over-optimisation curve, and why that?

d = √KL between the optimised policy and the initial one. It measures how far optimisation has moved the policy, so best-of-n and RL can be compared on one scale.

8. Courses & content

ResourceTypeUse it for
Nathan Lambert · RLHF BookFree online bookReward models, PPO, DPO-family methods, over-optimisation
Hugging Face TRL · DPO / KTO / ORPO trainersOfficial docsRun each method on a small model
DeepLearning.AI · Post-training of LLMsShort courseSFT, DPO and online RL, hands-on
DeepLearning.AI · Reinforcement Learning from Human FeedbackShort courseThe classic reward-model + RL pipeline
Hugging Face smol-course · Preference Alignment unitCourse (free)DPO in practice on a small model
Stanford CS336 · Assignment 5 (Alignment & reasoning RL)University course (free materials)SFT and RL for maths reasoning; optional DPO

Start with the RLHF Book for the concepts, then the TRL docs, because they're what you'll actually run the practice project with.

Full course map for all 12 stages →

9. Papers & docs