← All notes
Course chapters
On this page

Lesson 25 · Large language models

Pretraining, supervised fine-tuning and reinforcement learning

Follow a common assistant-training recipe from next-token pretraining to demonstrations and preference feedback. Inspect loss masks, reward models, KL regularisation and the distinction between PPO and DPO.

1. Continuing text and completing a request

Suppose we ask a base language model: “Write an email asking my landlord to repair a leaking pipe.” It might draft the email, or it might continue the request as the opening of an article about tenant complaints.

This is an illustrative possibility, not an observed prediction from a model running on this page. Pretraining can already build some instruction-following capability, but next-token prediction alone does not ensure reliable assistance.

The architecture supplies a way to calculate predictions. Training data and objectives influence which responses become likely. How do we encourage a useful answer rather than just a plausible continuation?

Pause and think

Could we show the model examples of requests followed by the responses we want, while keeping its next-token prediction machinery?

I've thought about it — show the answerHide answer

Yes. Supervised fine-tuning continues training on demonstrated responses conditioned on prompts.

The same model can learn a more useful response distribution without replacing its Transformer with a new architecture.

2. Pretraining: learn from broad text

A common causal language-model recipe begins with self-supervised training on a large text corpus. The text itself supplies the next-token targets:

Lpre=−EX∼D∑tlog⁡pθ(xt∣x<t).\mathcal L_{\mathrm{pre}} =-\mathbb E_{X\sim\mathcal D}\sum_t\log p_\theta(x_t\mid x_{<t}).

“Self-supervised” does not mean there is no target. It means we can construct the target from the data rather than asking a person to write a separate label for every prediction.

The objective connects this model to the N-gram and recurrent language models studied earlier. The tools for estimating the conditional distribution have changed, while next-token prediction remains a useful common thread.

Predicting varied text can reward learning syntax, factual associations, code patterns and some reasoning procedures. It does not logically force perfect understanding of the world. A model can also learn shortcuts, memorise text and reproduce errors in its training data.

1. Pretraining

Broad text → next-token learning → base model

2. Supervised fine-tuning

Prompt + demonstrated response → imitate desired behaviour

3. Preference optimisation

Comparisons or other feedback → adjust response preferences

Figure 25-1. A common training recipe. The stages have overlapping effects, and real recipes can repeat, combine or omit stages.

Dataset coverage, quality, filtering, duplication and the training process all matter. Scale is useful, but a larger corpus is not automatically a more truthful or helpful one.

Pretraining often requires substantial computation. It is misleading to say it is the only potentially expensive stage: later training can also consume significant resources, especially when generating many model responses or evaluating them.

These three stages are a common teaching framework, not a complete account of every assistant's training pipeline.

3. SFT: learn from demonstrated responses

Supervised fine-tuning, or SFT, uses examples such as a request paired with a useful response. A model-specific chat template marks roles, message boundaries and where the assistant response begins.

For a prompt xx and demonstrated answer yy:

LSFT=−E(x,y)∼Ddemo∑t∈Alog⁡pθ(yt∣x,y<t),\mathcal L_{\mathrm{SFT}} =-\mathbb E_{(x,y)\sim\mathcal D_{\mathrm{demo}}} \sum_{t\in\mathcal A}\log p_\theta(y_t\mid x,y_{<t}),

where A\mathcal A identifies the response targets included in the loss.

User · conditioning context

Write an email asking for a leaking pipe to be repaired.

Direct target-loss mask: 0

Assistant · demonstrated response

Please repair the leaking pipe…

Direct target-loss mask: 1

Figure 25-2. Assistant-only target loss is one SFT convention. Real chat templates include model-specific role and boundary tokens; other recipes can also train on user targets.

Assistant-only loss is a common convention, rather than a requirement for every SFT recipe. Some datasets and implementations also train on other parts of a conversation.

Crucially, a loss mask is different from an attention mask. The prompt is still an input used to generate the answer. Excluding direct prompt-target losses does not remove the prompt from attention, or mean that gradients cannot flow through computations involving its representations.

Fixed target probabilities; whitespace-separated teaching units.
TargetP(target)−ln PIncluded
Write0.900.105no
an0.800.223no
email0.700.357no
Please0.600.511yes
repair0.500.693yes
the0.400.916yes
leak0.301.204yes

Included targets: 4 · Total loss: 3.3242 · Mean loss: 0.8311

The prompt still conditions the answer. Only direct target-loss terms are masked. These numbers are fixed examples, not predictions from a trained model; a changed mean alone does not show improved quality.

Experiment 25-A. Toggle which fixed next-token target losses contribute to the objective.

The experiment uses fixed probabilities and whitespace-separated teaching units. Its units are not a production tokenizer's output. The loss is ordinary negative log probability, and selecting a different set of targets changes both the total and its averaging denominator.

SFT can improve formatting, task behaviour, tone and response quality. It is too narrow to say it only teaches manners or the answer format: the demonstrations can contain substantive problem-solving behaviour and preferences.

However, examples are incomplete and can be inconsistent or wrong. Imitating demonstrations does not guarantee good answers on unfamiliar requests. Preference feedback supplies a different kind of learning signal.

4. Learn a ranking signal from comparisons

Instead of asking a person to write one ideal answer, show several candidates for the same prompt and ask which they prefer. A pair can be represented as a prompt xx, chosen response y+y^+ and rejected response y−y^-.

A reward model assigns a scalar score rϕ(x,y)r_\phi(x,y). One common pairwise loss is:

LRM=−log⁡σ ⁣(rϕ(x,y+)−rϕ(x,y−)).\mathcal L_{\mathrm{RM}} =-\log\sigma\!\left(r_\phi(x,y^+)-r_\phi(x,y^-)\right).

Here σ\sigma is the logistic sigmoid. A larger positive chosen-minus-rejected score gap produces a smaller loss; a zero gap gives log⁡2\log2.

Same prompt → candidate responses A and B → labelled preference

Prompt + each response → reward model → scalar scores

Δ=rϕ(x,y+)−rϕ(x,y−),LRM=−log⁡σ(Δ)\Delta=r_\phi(x,y^+)-r_\phi(x,y^-),\qquad\mathcal L_{\mathrm{RM}}=-\log\sigma(\Delta)
Figure 25-3. Pairwise comparisons train a ranking signal. The score is not a calibrated truth, safety or quality probability.

A Transformer with a scalar output head is one way to build the scorer. Its parameters are trained to fit comparisons, separately from the language policy that produces responses.

The score depends on the prompt and response, not just the response in isolation. Comparisons also reflect the evaluators, instructions and examples sampled. Different people can reasonably disagree, and a single scalar may hide trade-offs between qualities.

A learned reward is therefore a proxy for the desired behaviour. It is not a universal measurement of truth, helpfulness or safety. It can fail on new distributions or reward superficial properties such as verbosity.

5. Update the policy, and limit drift

In a classic RLHF recipe, the language policy samples responses and an RL optimiser uses the reward signal to update the policy. A frozen reference policy, often derived from the SFT checkpoint, helps regularise that update.

A simplified sequence-level objective is:

J(θ)=Ex[Ey∼πθ(⋅∣x)rϕ(x,y)−βDKL ⁣(πθ(⋅∣x)∥πref(⋅∣x))].J(\theta)=\mathbb E_{x}\left[ \mathbb E_{y\sim\pi_\theta(\cdot\mid x)}r_\phi(x,y) -\beta D_{\mathrm{KL}}\!\left( \pi_\theta(\cdot\mid x)\parallel\pi_{\mathrm{ref}}(\cdot\mid x) \right)\right].

The KL term measures departure from the reference distribution. For sampled sequences, an associated log-ratio estimate is:

log⁡πθ(y∣x)πref(y∣x)=∑tlog⁡πθ(yt∣x,y<t)πref(yt∣x,y<t).\log\frac{\pi_\theta(y\mid x)}{\pi_{\mathrm{ref}}(y\mid x)} =\sum_t\log\frac{\pi_\theta(y_t\mid x,y_{<t})}{\pi_{\mathrm{ref}}(y_t\mid x,y_{<t})}.

The full expected KL is nonnegative; an individual sampled log ratio can be negative. Practical implementations use estimates and additional training machinery.

1. Policy samples responses to prompts
2. Reward model scores the sampled responses
3. Reference policy supplies a KL regularisation term
4. RL optimiser updates the policy using the training signal
5. Sample again with the updated policy
Figure 25-4. A simplified classic RLHF loop. PPO is one optimiser; a KL-regularised objective alone is not the complete PPO algorithm.

PPO is one policy optimiser used in classic RLHF. Its update also includes details such as probability-ratio clipping and advantage estimates. Writing “reward minus KL” describes a regularised objective, not the whole PPO algorithm.

If the policy finds responses that exploit mistakes in the scorer, the measured reward can rise while actual quality falls. This is reward hacking. KL regularisation can discourage large changes, but cannot guarantee its prevention or fix a bad reward model. Held-out evaluation and checking actual outputs remain necessary.

Expected reward: 0.5000

KL(policy ∥ reference): 0.0000 nats

Reward − β × KL: 0.5000

Pairwise reward-model loss: 0.6931

The policy example has only two possible responses and a fixed reference distribution [0.5, 0.5]. The separate score-gap calculation trains a reward model; it is not the policy objective. No PPO, DPO or model updates run here.

Experiment 25-B. Inspect a two-response reward/KL trade-off and a separate pairwise ranking loss.

The experiment uses only two possible responses. The reference assigns probability 0.50.5 to each, with rewards 11 and 00. Increasing the policy's probability of the rewarded response raises expected reward but also changes its KL. A larger penalty coefficient makes the same departure more expensive.

This is exact arithmetic over a tiny distribution, not an implementation of language-model RL. Its separate score-gap control demonstrates reward-model fitting, rather than a policy update.

DPO: optimise preferences directly

Direct Preference Optimization, or DPO, uses preference pairs with a fixed reference policy, without separately fitting a reward model or running the usual online reward-model RL loop during its training.

A standard loss uses:

LDPO=−log⁡σ ⁣(β[log⁡πθ(y+∣x)πref(y+∣x)−log⁡πθ(y−∣x)πref(y−∣x)]).\mathcal L_{\mathrm{DPO}}=-\log\sigma\!\left( \beta\left[ \log\frac{\pi_\theta(y^+\mid x)}{\pi_{\mathrm{ref}}(y^+\mid x)} -\log\frac{\pi_\theta(y^-\mid x)}{\pi_{\mathrm{ref}}(y^-\mid x)} \right]\right).

It compares how the policy changes the chosen response's likelihood relative to the rejected response and their reference likelihoods. This is a pairwise objective, not simply “increase the probability of every chosen answer” in isolation.

DPO is an alternative preference-training approach, not a compulsory stage after PPO or a guarantee of superior behaviour. Dataset quality, reference policy and optimisation choices still matter. RL training can also use feedback other than human comparisons, such as verifiable task rewards.

6. What you have discovered

  • Causal pretraining learns next-token prediction from text-derived targets and can develop broad capabilities without guaranteeing reliable assistance.
  • SFT trains on demonstrated responses, often with an assistant-target loss mask; the prompt remains conditioning context.
  • Pairwise preferences can train a reward model, whose scores are an imperfect proxy for the desired behaviour.
  • Classic RLHF updates a response policy with rewards and reference regularisation; PPO is one possible optimiser.
  • DPO provides another route to preference optimisation without the same separate reward-model training loop.

These stages influence overlapping capabilities. There is no guarantee that completing all three produces a flawless assistant, and useful models can use different recipes.

Next, we will examine KV caching, sparse attention and FlashAttention: engineering techniques that change how attention is executed and what work must be retained or repeated.

Check your understanding

1. Which sequence describes a common classic assistant-training recipe?
2. What is the main self-supervised objective in causal language-model pretraining?