Post-training: SFT, RLHF and DPO

Session 3 - 3 hours - Lecture + live-coding lab

Lambert Fatoux

Learning outcomes (today)

  1. Explain why a base model is not an assistant, and what each post-training stage fixes
  2. Write the SFT loss and explain loss masking and chat templates
  3. Trace the RLHF pipeline: reward model (Bradley–Terry) → PPO with a KL penalty
  4. Explain the intuition of DPO and say when it beats RLHF
  5. Write LoRA from scratch, fine-tune a 0.5B instruct model with it, and compare it with the original

Produced: a LoRA adapter + a loss curve + an off vs on comparison

Warm-up quiz 1/3: attention

Which formula is scaled dot-product attention?

  • A. \(\;\mathrm{softmax}\big(QK^\top / \sqrt{d_k}\big)\,V\)
  • B. \(\;\mathrm{softmax}\big(QV^\top / \sqrt{d_k}\big)\,K\)
  • C. \(\;\mathrm{softmax}\big(QK^\top\big)\,V / \sqrt{d_k}\)
  • D. \(\;QK^\top\,\mathrm{softmax}\big(V / \sqrt{d_k}\big)\)

✅ Answer: A

Queries are compared with keys (\(QK^\top\)), the softmax turns the scores into weights, and the weights average the values \(V\). Dividing by \(\sqrt{d_k}\) stops the dot products from growing with the dimension, so the softmax does not saturate.

Warm-up quiz 2/3: perplexity

A model reaches a validation loss of 2.3 (nats per token). Its perplexity is about…

  • A. 2.3
  • B. 10
  • C. 200
  • D. It cannot be computed from the loss

✅ Answer: B

Perplexity \(= e^{\text{loss}} = e^{2.3} \approx 10\): the model is as uncertain as if it picked uniformly among 10 tokens at each step.

Warm-up quiz 3/3: logits

For the next token, the model outputs logits \([2.0,\; 1.0,\; 0.0]\). Which statement is true?

  • A. The probabilities are \([0.67,\; 0.33,\; 0]\)
  • B. Logits always sum to 1
  • C. Adding 10 to every logit leaves the probabilities unchanged
  • D. The third token can never be sampled

✅ Answer: C

The softmax only depends on differences between logits: \([12, 11, 10]\) gives the same \([0.67,\; 0.24,\; 0.09]\). Remember this for Bradley–Terry later today!

Recap: where Session 2 left us

  • Pretraining = next-token prediction on trillions of tokens → a base model
  • Cost: \(C \approx 6ND\) → millions of GPU-hours for a frontier model
  • Memory for training with Adam: 16 bytes per parameter

Today: what happens between the base model and the assistant you use every day.

Why Session 3 exists (practice)

You will rarely pretrain. You will be asked to adapt models.

  • Can we make the model always answer in our JSON format / brand tone? → SFT
  • Why does the chatbot flatter users or write overly long answers? → reward hacking
  • Should we fine-tune or use RAG for our internal docs? → what SFT can and cannot teach
  • Can we fine-tune a model on one GPU, for 50 clients? → LoRA, adapters
  • Why did the new model version suddenly get worse at X? → post-training trade-offs

Today = the knobs that turn a raw model into a product.

Why post-train?

A base model is a document completer

  • Pretraining teaches: “what text usually comes next on the internet?”
  • The internet contains questions followed by… more questions, forum noise, toxic content, wrong answers, spam

What we want instead:

  • Follow instructions (“summarise this in 3 bullets”)
  • Hold a conversation with roles (user / assistant)
  • Be helpful, honest, harmless (the “HHH” criteria)
  • Refuse some requests, admit uncertainty, stop when done

Pretraining gives knowledge and skills. Post-training gives behaviour.

The post-training pipeline

SFT teaches the base model to imitate good answers, then the reward model and RL push it towards answers humans prefer; DPO does that second part in a single, simpler step.

Small compute, huge impact

💼 Business corner

InstructGPT (OpenAI, 2022): human labellers preferred the answers of a 1.3B post-trained model over those of the 175B GPT-3 base model, a model more than 100× smaller.

Post-training cost: ≈ 60 petaflop/s-days, vs ≈ 3,640 for GPT-3 pretraining, under 2% of the compute.

  • The same recipe (SFT → RM → PPO) powered ChatGPT (Nov. 2022): an estimated 100M users in 2 months
  • The base model already “knew” most of it; post-training made it usable
  • Since 2024, labs spend a growing share of compute on post-training, especially RL for reasoning

Three kinds of data

  • SFT, (prompt, ideal answer) demonstrations
    • 10k–1M examples written by humans or generated by a stronger model
  • Reward model, (prompt, chosen answer, rejected answer) comparisons
    • 50k–1M pairs humans (or AI) rank answers instead of writing them
  • RL, prompts only: the model generates, the reward model scores

🎲 Fun fact

InstructGPT’s labelling team was about 40 contractors. In 2025 Meta invested $14.3B for 49% of Scale AI, a data-labelling company: human feedback has become a strategic asset

Supervised fine-tuning (SFT)

SFT in one sentence

Keep training with the same next-token loss as pretraining, but on (prompt, answer) conversations, and only score the answer tokens.

\[ \mathcal{L}_{\text{SFT}}(\theta) = -\,\mathbb{E}_{(x,y)\sim\mathcal{D}} \sum_{t=1}^{|y|} \log \pi_\theta\!\left(y_t \mid x,\, y_{<t}\right) \]

  • \(x\) = prompt (system + user messages), \(y\) = assistant answer
  • \(\pi_\theta\) = the model, viewed as a policy that “chooses” tokens (RL vocabulary, used from now on)
  • Same code as Session 2: cross-entropy on shifted targets

Chat templates: roles become tokens

  • A model has no notion of “roles”: it only reads one string. Special tokens mark who speaks and where a turn ends
  • Never build this string by hand: tokenizer.apply_chat_template(messages) uses the template stored with the model; train and serve with the same template

Loss masking: learn to answer, not to ask

  • Labels of prompt tokens are set to −100: PyTorch’s cross_entropy ignores them (check doc)
  • Without masking, the model also learns to imitate users (and wastes capacity)
  • The end-of-turn token is trained: this is how the model learns to stop

SFT with TRL

from trl import SFTConfig, SFTTrainer

train = [
    {"prompt": [{"role": "user",
                 "content": "How do I boil an egg?"}],
     "completion": [{"role": "assistant",
                     "content": "Simmer it for 9 minutes."}]},
    ...,
]

# TRL applies the chat template
# and masks the prompt (completion_only_loss)
trainer = SFTTrainer(
    model="meta-llama/Llama-3.2-1B-Instruct",
    train_dataset=train,
    args=SFTConfig(output_dir="out", learning_rate=2e-5,
                   num_train_epochs=1),
)
trainer.train()

With a prompt / completion dataset, TRL applies the chat template and masks the prompt for you (completion_only_loss).

Where does SFT data come from?

  • Human-written: InstructGPT (~13k prompts), OpenAssistant (2023): 161k messages in 35 languages from 13,500+ volunteers, today’s lab
  • Distilled from a stronger model: Stanford Alpaca (2023), 52k instructions generated with an OpenAI model for < $600 in total
  • Curated, tiny: LIMA (2023), only 1,000 carefully chosen examples gave a 65B model strong assistant behaviour

The Superficial Alignment Hypothesis (LIMA): knowledge comes from pretraining; SFT mostly teaches the format and style of answers. Quality ≫ quantity.

Distillation wars: DeepSeek and the frontier labs

OpenAI Jan. 2025

  • Right after DeepSeek-R1: DeepSeek “may have inappropriately” used OpenAI outputs to train its models
  • Suspicious accounts blocked with Microsoft in 2024

Anthropic Feb. 2026

  • DeepSeek, Moonshot, MiniMax accused of distilling Claude
  • ~24,000 fake accounts, 16M+ exchanges (DeepSeek: ~150k)
  • Targeted: reasoning, tool use, coding

Distillation is cheap and effective, so frontier outputs are worth stealing (company allegations, not court rulings).

⚠️ Many providers’ terms of use forbid using their outputs to train competing models. Check the licence of synthetic datasets.

What SFT can and cannot do

Good at

  • Format & JSON
  • Narrow tasks
  • Distilling a big model into a small one

Bad at

  • New facts: increase hallucinations → RAG (S5)
  • Forgetting other skills
  • Beating its data
  • Preferences (A better than B)
  • Harmful requests: no negative feedback

SFT imitates. For safe, high-quality models, we must teach the model to prefer good outputs over bad ones.

The imitation ceiling

SFT can at best match its demonstrations; preferences let the model go further.

When behaviour slips: Grok, July 2025

  • xAI added one line to Grok’s system prompt: “not shy away from making claims which are politically incorrect, as long as they are well substantiated”
  • Within days, Grok posted antisemitic content, praised Hitler and called itself “MechaHitler”. xAI deleted the posts, removed the line and apologised

The internet’s worst content is still in the weights: post-training only teaches the model not to say it, and a single instruction can tip the balance.

Safety training is shallow

  • A few tokens deep: only the first tokens; force “Sure, here is…” → it goes on
  • 10 examples, $0.20: GPT-3.5 Turbo’s guardrails gone; benign data hurts too
  • One direction: remove the refusal direction (“abliteration”) → it never refuses

💼 Business corner

Fine-tune or self-host an open model? Its safety is now your job: re-test after every fine-tune.

Fine-tuning: business use cases

💼 Business corner

  • Cheaper inference: distil GPT-class quality on one task into a 1–8B model you host yourself (OpenAI even sells “distillation” as a product)
  • Format compliance: reliable JSON / XML for downstream systems, fewer retries
  • Privacy & sovereignty: fine-tune an open model on-premise, data never leaves the company

Rule of thumb: prompt first, then RAG, then fine-tune, and only with an eval set to prove it helps.

RLHF: learning from human preferences

Why preferences?

  • Writing the perfect answer is hard and slow, even for experts
  • Comparing two answers is fast, cheap and more consistent
  • SFT can only imitate; preferences tell the model what is better
  • Preference data scales: Anthropic’s HH-RLHF ≈ 160k comparisons, LMArena collects millions of votes

From comparisons to a score: Bradley–Terry

Assume each answer has a hidden reward \(r(x, y)\). The probability that \(y_w\) is preferred to \(y_l\) (\(y_w\) = chosen/winner, \(y_l\) = rejected/loser):

\[ P(y_w \succ y_l \mid x) = \sigma\big(r(x, y_w) - r(x, y_l)\big), \qquad \sigma(z) = \frac{1}{1 + e^{-z}} \]

Fun fact: you already know Bradley–Terry

🎲 Fun fact

  • Elo ratings in chess are a Bradley–Terry model: a 400-point gap ≈ 10:1 odds of winning
  • The LMArena / Chatbot Arena leaderboard from Session 1 fits a Bradley–Terry model on millions of “A vs B” human votes
  • The same 1952 statistical model ranks chess players, sports teams… and the reward of an LLM answer


If you’re bored during today’s class, you can try to rank LLMs by going to the arena

The reward model

  • Usually the SFT model with its LM head replaced by a single scalar output
  • Trained like a binary classifier: push the chosen answer’s score above the rejected one’s (Bradley–Terry)

Reward model in code

import torch.nn.functional as F

def reward_model_loss(reward_model, chosen, rejected):
    r_w = reward_model(**chosen).logits.squeeze(-1)     # (B,) one score per answer
    r_l = reward_model(**rejected).logits.squeeze(-1)   # (B,)
    return -F.logsigmoid(r_w - r_l).mean()
  • F.logsigmoid is the numerically stable version of log(sigmoid))
  • Only differences of rewards matter: the RM’s scale is arbitrary
  • Evaluate it like a classifier: accuracy on held-out pairs (typically 65–75%: humans disagree too!)

Why is this reinforcement learning?

Writing an answer is like playing a game, one token at a time:

RL concept For an LLM In a video game
Policy \(\pi_\theta\) The language model we train The player
State The prompt + the tokens written so far What is on the screen
Action Choosing the next token Pressing a button
Reward The reward model’s score \(r_\phi(x, y)\) The final score

The model writes a whole answer (many actions) and gets one score at the end. It must work out which tokens earned or lost points: there is no “correct next token” to copy, unlike SFT.

The RL objective: maximise reward, on a leash

Goal: maximise the reward, minus β × the distance from the SFT model (the KL divergence)

  • The reference = a frozen copy of the SFT model; the KL measures how far the policy drifts from it
  • β controls the leash:
    • β too large → the model barely changes
    • β too small → the model drifts into gibberish that fools the reward model
  • The answer \(y\) is sampled from the model itself: this is reinforcement learning, not supervised learning

PPO: the moving parts

  • The value model predicts the score, so PPO knows which answers beat expectations
  • Each update is clipped (≈ ±20%): one batch cannot change the model too much
  • The reward scores the full answer; the KL penalty applies per token

Reward hacking

The reward model is a proxy for human judgement. Optimise a proxy hard enough and it breaks (Goodhart’s law).

🎲 Fun fact

A classic RL example (OpenAI, 2016): an agent rewarded for points in a boat-racing game learnt to spin in circles collecting bonuses, never finishing the race, and still beat human scores.

Reward hacking in the wild

  • Length bias: RMs tend to prefer longer answers → RLHF models get verbose
  • Sycophancy: humans like being agreed with → models flatter and agree with wrong claims
  • Confident tone rated higher than hedged but correct answers

💼 Business corner

In April 2025, OpenAI rolled back a GPT-4o update after users found it excessively sycophantic. OpenAI explained it had weighted short-term user feedback (thumbs up/down) too heavily. A reward signal is a product decision with real consequences.

RLHF: verdict

Pros

  • Optimises what humans prefer, not just what they wrote
  • Online: the model explores answers that no annotator wrote
  • Behind InstructGPT, ChatGPT, Claude, early Llama 2 chat

Cons

  • 4 models in memory, generation inside the training loop
  • Many hyper-parameters, unstable, hard to reproduce
  • Reward hacking needs constant monitoring

You do not need to implement PPO. You need to know why it is expensive and fragile.

Variants: RLAIF / Constitutional AI (Anthropic, 2022) replace most human labels with an AI judge guided by written principles → far cheaper feedback at scale.

DPO: preferences without RL

DPO in plain words: one training example

  1. Data: a prompt, a better and a worse answer (picked by a labeller)
  2. Measure how likely the model finds each, compared with its frozen copy
  3. Push the better one up, the worse one down; β limits the drift

DPO: the core idea

  • Implicit reward = how much more likely the model makes an answer than its frozen copy: the model is the reward model
  • No reward model, no sampling, no value model: two fixed answers, scored by two models

Quiz: DPO at step 0

Before any update, the model equals its frozen copy. What is the DPO loss?

  • A. 0
  • B. ln 2 ≈ 0.69
  • C. 1
  • D. It depends on β

✅ Answer: B

Both answers are exactly as likely as before, so the gap is 0 and the model gives each answer a 50% chance of winning: loss = −log(0.5) = ln 2, whatever β is. If your first DPO loss is not 0.69, there is a bug.

DPO in code

import torch.nn.functional as F

def dpo_loss(logp_w, logp_l, ref_logp_w, ref_logp_l, beta=0.1):
    # each argument: (B,) summed log-probs of the answer tokens
    margin = beta * ((logp_w - ref_logp_w) - (logp_l - ref_logp_l))
    return -F.logsigmoid(margin).mean()

With TRL, on a dataset of {"prompt", "chosen", "rejected"}:

from trl import DPOConfig, DPOTrainer

# with LoRA: adapter off = reference
trainer = DPOTrainer(
    model=model, ref_model=None,
    args=DPOConfig(output_dir="dpo", beta=0.1, learning_rate=5e-6),
    train_dataset=preferences, peft_config=lora,
)
  • ref_model=None: with a LoRA adapter (next part), switching it off gives the frozen reference for free

RLHF vs DPO

  • DPO: simple, stable, cheap → the default for open models since 2023 (Zephyr-7B, Llama 3, Tülu 3…)
  • RLHF/online RL: can go beyond the dataset by exploring → still used at frontier labs
  • DPO is limited to the answers present in the preference data (offline)

The *PO family (2023–2025)

  • KTO, only needs 👍 / 👎 per answer, no pairs (like real product feedback!)
  • IPO, ORPO, SimPO: variants with bounded loss or no reference model
  • Online / iterative DPO, regenerate answers with the current model, re-rank, repeat

💼 Business corner

Most products already collect thumbs up / down. KTO-style methods turn that log into training data, but remember the GPT-4o sycophancy story: user approval is not the same as quality.

RL with verifiable rewards (RLVR)

For maths and code, you don’t need a reward model: you can check the answer.

  • Reward = 1 if the final answer is correct / the unit tests pass, else 0
  • No reward model to hack (mostly) unlimited “labels” for free
  • GRPO (DeepSeek, 2024): PPO without a value model, sample a group of answers per prompt, each answer is scored against the group’s average

🎲 Fun fact

DeepSeek-R1-Zero (Jan. 2025) was trained with pure RL on verifiable rewards, without SFT. Its answers spontaneously got longer and started to re-check their own work, the authors called it an “aha moment”. This is how reasoning models (o1, R1, Claude extended thinking…) learn to “think” (link with test-time compute, Session 2).

A modern post-training recipe

Model (year) Recipe
InstructGPT (2022) SFT → reward model → PPO
Zephyr-7B (2023) SFT on synthetic chats → DPO on AI-ranked pairs
Llama 3 (2024) SFT → rejection sampling → DPO, several rounds
Tülu 3 (AI2, 2024, fully open) SFT → DPO → RL with verifiable rewards
DeepSeek-R1 (2025) small SFT → GRPO with verifiable rewards → SFT → RL

Stages are mixed and repeated. Every arrow needs an evaluation to decide whether it helped (course doctrine, Session 8).

Case study: AlphaProof, RL for olympiad maths

Goal: prove IMO problems in Lean, a programming language where a computer checks every proof step (Google DeepMind, 2024)

  1. Translate: a fine-tuned Gemini turns ~1M human maths problems into 80M formal statements, the RL “prompts”
  2. Reward = the proof checker: 1 if Lean accepts the proof, 0 otherwise. Perfectly verifiable: no reward model to hack

IMOs

  • IMO 2024: 28/42, silver, one point short of gold (some problems took days)
  • IMO 2025: Gemini Deep Think, gold, in plain English, within the time limit

LoRA: fine-tuning on a budget

The memory problem

Full fine-tuning updates every weight and stores gradients + Adam states for each (Session 2: 16 B/param).

The LoRA idea

Fine-tuning updates have low intrinsic rank: freeze \(W_0\), learn a small update \(\Delta W = BA\).

Counting LoRA parameters

Llama-3.2-1B (1.24B params): 16 layers, d_model = 2048, grouped-query attention (K and V project to 512)

  • The adapter file weighs ~14 MB (fp32) instead of ~2.5 GB for the full model
  • Also targeting the MLP (target_modules="all-linear") usually helps, for ~3–4× more parameters

LoRA hyper-parameters

Parameter Typical value Intuition
r (rank) 8–64 How many directions the update may use: more capacity, more memory
lora_alpha α = 2r Scale factor \(\frac{\alpha}{r}\); keeping α = 2r keeps it at 2 when you change r
target_modules attention or "all-linear" Where you plug the adapters; adding the MLP layers gives more room to learn
learning rate 1e-4 to 2e-4 The adapter is small and starts at zero (\(B = 0\)): ~10× full fine-tuning

LoRA learns less and forgets less than full fine-tuning: good for style and format, weaker for deep new skills.

QLoRA: a 65B model on one GPU

  • Store the frozen base model in 4-bit (NF4 quantisation): ~0.5 byte per parameter
  • Train LoRA adapters in 16-bit on top of it
  • The QLoRA paper fine-tuned a 65B model on a single 48 GB GPU

🎲 Fun fact

QLoRA’s showcase model, Guanaco, was fine-tuned on OpenAssistant, the dataset of today’s lab, in 24 hours on one GPU, and reached ~99% of ChatGPT’s score on the Vicuna benchmark (as judged by GPT-4).

Adapters are a business model

💼 Business corner

  • One base model, many adapters: serve 100 customers with 100 × 14 MB adapters on the same GPU (multi-LoRA serving in vLLM, LoRAX, cloud fine-tuning APIs)
  • Swap at runtime: a “legal” adapter, a “support” adapter, a “French tone” adapter
  • Cheap experiments: fine-tuning a 1B model with LoRA costs minutes on a single GPU, i.e. cents to a few euros
  • Ship small files: customer-specific behaviour without redistributing the base model weights
  • On-device: Apple’s on-device assistant model uses LoRA adapters for each feature (summaries, mail replies…)

In the lab, set_lora(model, False) gives you the original model for free: the perfect A/B baseline.

Case study: ARC-AGI, puzzles that resist memorisation

The challenge: colour-grid puzzles, 2–3 examples each; every puzzle is new, so memorising the internet does not help

  • Fine-tune at test time: LoRA on each puzzle’s few examples (+ rotations, flips, colour swaps) → ~55% (ARC Prize 2024)
  • RL reasoning model: o3, 87.5% on ARC-AGI-1 (Dec. 2024), with 1,024 samples per task
  • ARC-AGI-3 (2026): interactive games with no instructions; the harness alone moved one model from 62.7% to 99.9%: always ask how a score was measured (Session 8)

ARC-AGI website

Source: ARC Prize: GPT-6 Astra on ARC-AGI-3

Practice session

Lab overview

Goal: write LoRA yourself, fine-tune Qwen2.5-0.5B-Instruct on OpenAssistant answers, then compare it with the original model.

Part 1  Write the LoRA layer               your turn (3 lines) + checks
Part 2  Add it to q_proj and v_proj        given
Part 3  Fine-tune on 200 examples          your turn (training step, 4 lines)
Part 4  Adapter off vs on, save it         given
Bonus   Same parameter count with PEFT     given
  • You complete two cells, marked Your turn; every other cell is Given: read it, run it
  • Runs on a laptop: about 3 minutes of training on an Apple M2, faster on a Colab GPU

Done means: the checks pass, loss.png, adapter.pt, and two answers compared off vs on.

Lab part 1: the LoRA layer

class LoRALinear(nn.Module):
    def __init__(self, base: nn.Linear, r=8, alpha=16, dropout=0.05):
        ...
        self.A = ...  # Your turn: nn.Linear(in_features -> r, no bias)
        self.B = ...  # Your turn: nn.Linear(r -> out_features, no bias)
        nn.init.zeros_(self.B.weight)  # given: B starts at zero

    def forward(self, x):
        out = self.base(x)
        if self.enabled:
            out = out + ...  # Your turn: B(A(dropout(x))) * scaling
        return out
  • nn.Linear with bias=False is just a matrix: A goes down to r, B back up
  • B starts at zero, so at step 0 the model is exactly the original one
  • Given checks follow: shapes, same output at step 0, r × (in + out) trainable parameters, BA merges into W

Lab part 2: add LoRA to the model

  • add_lora(model) freezes everything, then wraps every q_proj and v_proj in a LoRALinear
  • A check confirms the logits are unchanged after wrapping
48 LoRA layers, 540,672 trainable parameters
= 0.11% of the model; outputs unchanged
  • 24 layers × 2 projections; each adds 8 × (896 + 896) or 8 × (896 + 128) parameters

Lab part 3: data and training step

  • Data (given): first user message + the answer ranked best (rank == 0), English only
  • 200 training and 24 validation examples, one example per step
  • Prompt tokens get the label -100: the loss is on the answer only
for step, batch in enumerate(train, start=1):
    # Your turn: forward pass, backward pass, optimiser step, reset gradients
    loss = ...
  • model(**batch).loss computes the shifted next-token loss when labels are passed
  • The optimiser only receives A and B, learning rate 2e-4

Lab part 3: the loss curve

  • One run on an M2: validation loss 1.49 → 1.45 after 200 steps
  • The model is already an instruct model: the loss starts low, gains are modest
  • The train loss is noisy: one example per step
  • Validation loss going up while train loss goes down → over-fitting: stop earlier

Lab part 4: adapter off vs on

for q in PROMPTS:
    set_lora(model, False)   # the original instruct model
    original = answer(q)
    set_lora(model, True)    # with the adapter
    tuned = answer(q)
  • Greedy decoding (do_sample=False) → differences come from the weights, not from sampling luck
  • Save only A and B: adapter.pt is 2.2 MB, the full model is 2.0 GB
  • Bonus: PEFT’s LoraConfig(r=8, target_modules=["q_proj", "v_proj"]) trains the same 540,672 parameters

Reflection

Answer with evidence from your loss curve and your two comparisons:

  1. What changed between the original and the LoRA model? Is it style or knowledge?
  2. Did the fine-tuned model get better, worse, or just different?
  3. What did the OpenAssistant data teach that you did not want (length, tone, errors)?
  4. Where would preference data (DPO) help more than more SFT data?
  5. Cost: trainable parameters, training time, adapter size. Would you ship it?

Knowledge check

  1. Why does a base model answer a question with more questions?
  2. Why are prompt tokens masked in SFT, but the end-of-turn token is not?
  3. A reward model gives \(r_w = 0.5\) and \(r_l = 1.5\). What is \(P(y_w \succ y_l)\)? Is the RM right?
  4. What does the KL term protect against? What happens when β → 0?
  5. What is DPO’s “implicit reward”, and why does DPO need no reward model?
  6. How many trainable parameters does LoRA r = 8 add to a 4096 × 4096 matrix?

Key takeaways

  • Pretraining gives knowledge; post-training gives behaviour, for a few % of the compute
  • SFT = next-token loss on answers only, with the model’s own chat template; it imitates, it does not judge
  • RLHF = reward model (Bradley–Terry) + RL with a KL leash; powerful, expensive, prone to reward hacking
  • DPO turns preferences into a simple classification loss: chosen more likely, rejected less likely; no RM, no sampling
  • Verifiable rewards (maths, code) power today’s reasoning models
  • LoRA / QLoRA make fine-tuning a 1B–70B model affordable; adapters are small, swappable products

Checklist (close)

Before you leave, you can explain:

Next session

Session 4, Advanced prompting and structured outputs: getting the behaviour you want without training.

  • JSON-schema and constrained decoding, tool calling
  • Few-shot, chain-of-thought, self-consistency
  • Prompt injection: see the attack land, then defend

Bring your off vs on answers: we will compare a fine-tuned model with a well-prompted one on cost and accuracy.