Session 3 - 3 hours - Lecture + live-coding lab
Produced: a LoRA adapter + a loss curve + an off vs on comparison
Which formula is scaled dot-product attention?
✅ 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.
A model reaches a validation loss of 2.3 (nats per token). Its perplexity is about…
✅ 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.
For the next token, the model outputs logits \([2.0,\; 1.0,\; 0.0]\). Which statement is true?
✅ 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!
Today: what happens between the base model and the assistant you use every day.
You will rarely pretrain. You will be asked to adapt models.
Today = the knobs that turn a raw model into a product.
What we want instead:
Pretraining gives knowledge and skills. Post-training gives behaviour.
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.
💼 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.
🎲 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
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) \]
tokenizer.apply_chat_template(messages) uses the template stored with the model; train and serve with the same templatecross_entropy ignores them (check doc)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).
The Superficial Alignment Hypothesis (LIMA): knowledge comes from pretraining; SFT mostly teaches the format and style of answers. Quality ≫ quantity.
OpenAI Jan. 2025
Anthropic Feb. 2026
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.
Good at
Bad at
SFT imitates. For safe, high-quality models, we must teach the model to prefer good outputs over bad ones.
SFT can at best match its demonstrations; preferences let the model go further.
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.
💼 Business corner
Fine-tune or self-host an open model? Its safety is now your job: re-test after every fine-tune.
💼 Business corner
Rule of thumb: prompt first, then RAG, then fine-tune, and only with an eval set to prove it helps.
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
If you’re bored during today’s class, you can try to rank LLMs by going to the arena
F.logsigmoid is the numerically stable version of log(sigmoid))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.
Goal: maximise the reward, minus β × the distance from the SFT model (the KL divergence)
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.
💼 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.
Pros
Cons
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.
Before any update, the model equals its frozen copy. What is the DPO loss?
✅ 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.
With TRL, on a dataset of {"prompt", "chosen", "rejected"}:
ref_model=None: with a LoRA adapter (next part), switching it off gives the frozen reference for free💼 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.
For maths and code, you don’t need a reward model: you can check the answer.
🎲 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).
| 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).
Goal: prove IMO problems in Lean, a programming language where a computer checks every proof step (Google DeepMind, 2024)
IMOs
Full fine-tuning updates every weight and stores gradients + Adam states for each (Session 2: 16 B/param).
Fine-tuning updates have low intrinsic rank: freeze \(W_0\), learn a small update \(\Delta W = BA\).
Llama-3.2-1B (1.24B params): 16 layers, d_model = 2048, grouped-query attention (K and V project to 512)
target_modules="all-linear") usually helps, for ~3–4× more 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.
🎲 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).
💼 Business corner
In the lab,
set_lora(model, False)gives you the original model for free: the perfect A/B baseline.
The challenge: colour-grid puzzles, 2–3 examples each; every puzzle is new, so memorising the internet does not help
Goal: write LoRA yourself, fine-tune Qwen2.5-0.5B-Instruct on OpenAssistant answers, then compare it with the original model.
Done means: the checks pass, loss.png, adapter.pt, and two answers compared off vs on.
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 outnn.Linear with bias=False is just a matrix: A goes down to r, B back upB starts at zero, so at step 0 the model is exactly the original oner × (in + out) trainable parameters, BA merges into Wadd_lora(model) freezes everything, then wraps every q_proj and v_proj in a LoRALinear8 × (896 + 896) or 8 × (896 + 128) parametersrank == 0), English only-100: the loss is on the answer onlymodel(**batch).loss computes the shifted next-token loss when labels are passedA and B, learning rate 2e-4do_sample=False) → differences come from the weights, not from sampling luckA and B: adapter.pt is 2.2 MB, the full model is 2.0 GBLoraConfig(r=8, target_modules=["q_proj", "v_proj"]) trains the same 540,672 parametersAnswer with evidence from your loss curve and your two comparisons:
Before you leave, you can explain:
Session 4, Advanced prompting and structured outputs: getting the behaviour you want without training.
Bring your off vs on answers: we will compare a fine-tuned model with a well-prompted one on cost and accuracy.
Albert School - Post-training: SFT, RLHF and DPO