How are LLMs trained? Explain pre-training, fine-tuning and RLHF.

Learning path, stage 1 of 5: How LLMs work · question 6 of 10

Training has three layers. Pre-training on trillions of tokens of next-token prediction gives knowledge and general skill. Supervised fine-tuning on curated instruction/response pairs teaches the assistant format. Preference optimisation (RLHF, RLAIF or DPO) teaches which of several possible answers people actually prefer: more helpful, more honest, safer.

1. Pre-training

  • Self-supervised: the text itself is the label.
  • This is by far the largest share of the compute. Scaling laws guide how to split a budget between model size and data. Chinchilla showed many earlier models were under-trained on data.

2. Supervised fine-tuning (SFT)

  • Thousands to millions of high-quality demonstrations: prompt → ideal answer.
  • Turns a text-completer into something that follows instructions.

3. Preference training

  • RLHF: people rank outputs → train a reward model → optimise the policy against it with RL (usually PPO), with a KL penalty so it doesn't drift too far from the SFT model.
  • RLAIF / Constitutional AI: an AI model gives the feedback, guided by written principles. This reduces the need for human labels.
  • DPO: skips the separate reward model and optimises directly on preference pairs. It is simpler and more stable.

Trend worth mentioning

Reasoning models add reinforcement learning on verifiable tasks (maths, code with tests), which teaches longer step-by-step thinking.

Sources

Code example

tsx
1// The shape of preference data used by RLHF reward models and DPO.
2interface PreferencePair {
3 prompt: string;
4 chosen: string; // the response people preferred
5 rejected: string; // the worse response
6}
7
8const dataset: PreferencePair[] = [
9 {
10 prompt: "How do I reverse an array in JS without mutating it?",
11 chosen: "Use `arr.toReversed()` (ES2023) or `[...arr].reverse()`.",
12 rejected: "Call arr.reverse(), it returns a new array.", // wrong: it mutates
13 },
14];
15
16// The DPO loss for one pair, given log-probs from the policy and a frozen reference model:
17// loss = -log σ( β * [(logπ(chosen) - logRef(chosen)) - (logπ(rejected) - logRef(rejected))] )
18const sigmoid = (x: number) => 1 / (1 + Math.exp(-x));
19export function dpoLoss(pc: number, rc: number, pr: number, rr: number, beta = 0.1) {
20 return -Math.log(sigmoid(beta * ((pc - rc) - (pr - rr))));
21}

To run it: follow the one-time setup guide, add npm i @anthropic-ai/sdk, save the code as a .ts file and run npx tsx file.ts. Anything marked declare is a part you supply.

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the AI Agents & LLMs set.

Open in study app