rumblr Work in progressWIP

● The AI Primer · Lesson 10 · Part 2: how it is trained and judged

Training stages

how a text predictor becomes an assistant

This lesson covers The stages that turn a random neural network into a chat assistant, and when to fine-tune instead of prompt

Members · open during launch 36 min13 figures and diagrams8 interactive

What this is

What are the training stages?

An AI chat assistant is a language model trained in three stages, and each stage explains part of how it behaves. Pretraining has it guess the next word across a vast amount of text, which gives it knowledge but leaves it continuing text instead of answering. Supervised fine-tuning trains it on examples of good answers, which teaches it the shape of a reply. Preference tuning trains it on pairs of replies and which one people preferred, which shapes its tone. After the stages come the cheaper ways you adapt a finished assistant yourself, and distillation, which trains a small assistant to stand in for a big one.

Why it matters: The day rewording a prompt stops fixing a behaviour, someone asks whether to fine-tune, and the stage that taught the behaviour tells you which lever will change it. An AI model that lacks a fact needs retrieval, not training.

At a glance

Key takeaways

  1. Pretraining predicts the next token across web-scale text and gives a model its knowledge; SFT teaches it the format of an answer; preference tuning shapes its tone, helpfulness and safety.
  2. SFT is the pretraining loss with the prompt masked out, so only the reply is graded.
  3. RLHF trains a reward model on pairs of answers people compared, then tunes the language model to score high against it; DPO learns from the same pairs directly, with no reward model.
  4. LoRA trains a small low-rank correction B·A beside frozen weights: 0.39% of a layer's parameters at rank 8, 3.1% at rank 64, and once merged it adds no serving time.
  5. Fine-tuning changes behaviour; retrieval (RAG) supplies knowledge. Try a better prompt and retrieval first.
  6. Distillation trains a small student on a big teacher's softened probabilities, so a task costs less to run.

How it works, from scratch

A chat assistant is trained in stages. The model's vendor runs the first three, and you adapt what comes out of them:

Figure 1 · Diagram

Reading it: read left to right. Each box is a stage, and each arrow hands the model on to the next. Pretraining takes months and millions of dollars, and gives a base model that knows facts but only continues text. Supervised fine-tuning (SFT) teaches it the format of an answer, and preference tuning shapes its tone, helpfulness and safety. A fact the model knows therefore came from pretraining, and its habit of answering in tidy bullet points from SFT and preference tuning. You work in the last box.

Press something you have seen a chat assistant do, and the stage that taught it lights up.

Chapter 1

Pretraining: predict the next token

Every later stage starts from a pretrained model. Pretraining gives a language model one task: at every position in a stretch of text, guess the token that comes next (a token is a word or a piece of a word). Grammar, facts, arithmetic and coding conventions all help with that guess, so a model that has practised it across web-scale text has picked them all up.

Each guess earns a penalty of −ln p, where p is the probability the model gave the token that really came next. The penalty is zero when p = 1 and grows as p shrinks. The pretraining loss is the average penalty over every guess, and training adjusts the weights to push it down. A 5-token sequence gives 4 guesses: token 1 predicts token 2, and so on, and the last token has nothing after it to check. Suppose the model gave the true next tokens probabilities 0.25, 0.25, 0.5 and 0.5. The penalties are 1.386, 1.386, 0.693 and 0.693, and the loss is their average, 1.040.

Figure 2 · Diagram

Reading it: each position guesses the token after it, using only the tokens before it. All the guesses are scored at once, and their average penalty is the loss. A text of n tokens gives n − 1 guesses, and the answer to each is the next token of the text itself, so the text needs no labelling.
The formula and its symbols

Symbols

Symbol Meaning here Shape / range
the loss: one number, lower is better ≥ 0
number of tokens in the sequence integer
add up the term for every position i from 1 to n−1
the i-th token (an integer id) 0 … vocab−1
all tokens up to and including position i (the context)
probability the model with weights θ gives the true next token, given the context. The bar "∣" reads "given" 0 … 1
all the model's weights millions to trillions of numbers
natural logarithm. ln 1 = 0 and ln of a small number is very negative, so −log turns "probability of being right" into "penalty"

In words: the loss is the average, over every position, of minus the log of the probability the model gave to the token that actually came next.

On the worked example: n = 5, the four probabilities are 0.25, 0.25, 0.5, 0.5, so the loss is −(ln 0.25 + ln 0.25 + ln 0.5 + ln 0.5) / 4 = (1.386 + 1.386 + 0.693 + 0.693) / 4 = 1.040.

In Python
import math
# p_θ(t_{i+1} | t_{1..i}) for each of the guesses
p = [0.25, 0.25, 0.5, 0.5]
# 5 tokens give n − 1 = 4 guesses
n = len(p) + 1
[round(-math.log(p_i), 3) for p_i in p]  # → [1.386, 1.386, 0.693, 0.693]
L_pretrain = -sum(math.log(p_i) for p_i in p) / (n - 1)
print(f"{L_pretrain:.3f}")  # → 1.040

New to Σ, ∂ or ‖x‖? The symbols reference decodes each one as a few lines of Python.

In code: per_position_losses scores every guess, and next_token_loss averages them. View source

What pretraining produces is a base model. Its knowledge stops at the date its training text was collected (the knowledge cutoff). And it does the one thing it was trained to do, continue text: ask it "What is the capital of France?" and it may continue with "What is the capital of Spain?", because lists of questions are common on the web.

Set the probability the model gave each true next token, and watch each penalty and the loss move.

Chapter 2

Supervised fine-tuning (SFT)

To turn a base model that continues text into one that answers, supervised fine-tuning (SFT) trains it further on examples of good answers, each a prompt followed by the reply wanted. The loss is the pretraining loss with one change. The model reads the whole example, but only the guesses that predict a reply token are graded, so it learns to write replies and not prompts.

Take the same 5 tokens, and say the first 3 are the prompt and the last 2 the reply. Only the 2 guesses that predict a reply token count, with penalties 0.693 and 0.693, so the SFT loss is 0.693. The two guesses that predict prompt tokens (1.386 each) are left out.

Figure 3 · Diagram

Reading it: the whole sequence flows through the model, so each reply token is predicted with the prompt in view. Only the dotted arrows reach the loss, and they come from the predictions of reply tokens. The list of which positions are graded, true or false for each, is the mask, and it is the only difference between pretraining code and SFT code.
The formula and its symbols

Symbols

Symbol Meaning here Shape / range
the mask: 1 if token i+1 belongs to the reply, else 0 0 or 1
how many predictions are graded (the reply length) integer
everything else as in the pretraining formula

In words: average the next-token penalty over the reply tokens only.

On the worked example: m = (0, 0, 1, 1), so the loss is (0.693 + 0.693) / 2 = 0.693.

In Python
import math
p = [0.25, 0.25, 0.5, 0.5]
# 1 only where the target is a reply token
m = [0, 0, 1, 1]
L_SFT = -sum(m_i * math.log(p_i) for m_i, p_i in zip(m, p)) / sum(m)
round(L_SFT, 3)  # → 0.693

Figure 4 · Chart

t1→t2 t2→t3 t3→t4 t4→t5 prediction (grey = prompt, masked; blue = reply) 0.0 0.2 0.4 0.6 0.8 1.0 1.2 1.4 1.6 1.8 penalty −ln p(true next token) SFT grades only the reply pretraining loss 1.040 (all positions) SFT loss 0.693 (reply only)

Only the two reply positions count: SFT loss 0.693 versus 1.040 averaged over every position

Reading it: each bar is one guess from the example, and its height is the penalty −ln p. Grey bars predict prompt tokens and are masked out; blue bars predict reply tokens and are the only ones SFT counts. The two dashed lines are the averages: 1.040 over every bar (pretraining) and 0.693 over the blue ones (SFT).

In code: response_mask marks the graded positions, and sft_loss averages the penalties over them. View source

SFT needs far less data than pretraining, thousands to hundreds of thousands of examples, and their quality counts for more than their number: a few thousand excellent examples do better than many more mediocre ones. If you fine-tune a model yourself and forget the mask, it learns to write the user's prompts as well as the replies.

Move the line between prompt and reply, and watch which guesses are graded and where the SFT average lands.

Chapter 3

Preference tuning: RLHF and DPO

SFT shows the model what a good answer looks like, one example at a time. It cannot tell the model which of two acceptable answers is better: more helpful, better in tone, safer. Which answer is better is hard to capture in one written example, but easy to judge with two answers side by side. Preference tuning trains on those judgements: shown two responses to the same prompt, a person (or a model following written principles) picks the better one. There are two ways to learn from the picks.

3a. RLHF: a reward model, then reinforcement learning

In reinforcement learning from human feedback (RLHF), a reward model first learns to predict the picks by giving each response a score. Reinforcement learning then tunes the language model to write responses that score high. Two scores become a prediction of which response wins through the Bradley-Terry model, built on the sigmoid function σ(z) = 1 / (1 + e^−z), which squashes any number into a probability between 0 and 1 (σ(0) = 0.5, σ(2) = 0.881).

Say the reward model scores the chosen answer 3.0 and the rejected one 1.0. The gap is 2, so it predicts that the chosen answer wins with probability σ(2) = 0.881, and its loss on this pair is −ln 0.881 = 0.127. Had it scored both 1.0, it would predict a coin flip (0.5) and pay ln 2 = 0.693.

Figure 5 · Diagram

Reading it: the loop trains two models, one after the other. First, labelers compare pairs and the reward model learns to agree with them. Then the language model writes new responses, the reward model scores them, and reinforcement learning (usually PPO) moves the language model towards higher scores, with a penalty for drifting far from where it started.
The formula and its symbols

Symbols

Symbol Meaning here Shape / range
the preferred ("winning") and rejected ("losing") responses text
"is preferred to"
the reward model's score for response y any real number
sigmoid, : turns a score gap into a probability 0 … 1
Euler's number, 2.718…; is "e to the power −z"
the reward model's loss on this pair ≥ 0

In words: the chance the preferred answer wins is the sigmoid of the score gap, and the reward model is penalised by minus the log of the probability it gave to the choice people actually made.

On the worked example: r(y_w) = 3, r(y_l) = 1, gap 2, σ(2) = 0.881, loss −ln 0.881 = 0.127.

In Python
import math
def sigma(z):
    return 1 / (1 + math.exp(-z))
r_w, r_l = 3.0, 1.0
# P(y_w ≻ y_l)
round(sigma(r_w - r_l), 3)  # → 0.881
# L_RM
round(-math.log(sigma(r_w - r_l)), 3)  # → 0.127
# equal scores: a coin flip, ln 2
round(-math.log(sigma(1.0 - 1.0)), 3)  # → 0.693

In code: preference_probability turns two scores into the chance that the first wins (the Bradley-Terry model), and reward_model_loss scores the reward model on one pair. View source

3b. DPO: preferences without a reward model

RLHF trains a reward model, then runs reinforcement learning against it. Direct preference optimization (DPO) learns from the same pairs in one ordinary training run, with no reward model and no reinforcement learning. It keeps a frozen copy of the model it starts from, the reference (usually the SFT model), and trains the other copy, the policy, to make the chosen answer more likely and the rejected one less likely. Both changes are measured against the reference, and a setting β (beta) holds the policy close to it.

The likelihoods are compared as log-probabilities: the log of the probability the model gives a whole response, which is the sum of its tokens' log-probabilities (more negative means less likely). Say the reference gives both answers −11. After some training the policy gives the chosen answer −10 (more likely than before) and the rejected one −12 (less likely). With β = 0.1 the margin is 0.1 × ((−10 − −11) − (−12 − −11)) = 0.1 × (1 + 1) = 0.2, and the loss is −ln σ(0.2) = 0.598, down from ln 2 = 0.693 when the policy still matched the reference.

Figure 6 · Diagram

Reading it: each preference pair is scored twice, by the policy and by the frozen reference. The margin measures how much more the policy has raised the chosen answer than the rejected one, relative to the reference. The loss is the reward model's loss again, with the reward read straight off the policy's own probabilities, so there is no separate reward model and no reinforcement-learning loop.
The formula and its symbols

Symbols

Symbol Meaning here Shape / range
the policy: the model being trained, with weights θ; π(y) is the probability it gives response y 0 … 1
the frozen reference model (usually the SFT model) 0 … 1
the log-ratio: how much more likely training has made y. β times it is the implicit reward , so the bracket scaled by β is any real
beta, the leash to the reference: it sets how much a change in log-probability counts, so a larger β satisfies the loss with a smaller departure and keeps the policy closer to the reference; a smaller β lets the preferences pull it further away typically 0.1 to 0.5
, sigmoid and natural log, as above

In words: raise the probability of the chosen answer and lower the rejected one, measured relative to the frozen starting model, and penalise the model by minus the log-sigmoid of that scaled gap.

On the worked example: β = 0.1, log-ratios +1 (chosen) and −1 (rejected), so implicit rewards r̂ = 0.1 × 1 = +0.1 and 0.1 × (−1) = −0.1, margin 0.1 − (−0.1) = 0.2, σ(0.2) = 0.550, loss 0.598. The gradient's size is β × (1 − σ(margin)) = 0.1 × 0.450 = 0.045: pairs the policy already ranks correctly get gentle updates, and pairs it ranks the wrong way get strong ones.

In Python
import math
def sigma(z):
    return 1 / (1 + math.exp(-z))
beta = 0.1
# chosen answer: policy, reference
logpi_w, logpi_ref_w = -10.0, -11.0
# rejected answer: policy, reference
logpi_l, logpi_ref_l = -12.0, -11.0
# implicit rewards r̂ = β × log-ratio
r_w = beta * (logpi_w - logpi_ref_w)
r_l = beta * (logpi_l - logpi_ref_l)
print(f"{r_w:.1f} {r_l:.1f}")  # → 0.1 -0.1
margin = r_w - r_l
print(f"{margin:.1f} {sigma(margin):.3f}")  # → 0.2 0.550
# L_DPO
round(-math.log(sigma(margin)), 3)  # → 0.598
# how hard this pair pushes
round(beta * (1 - sigma(margin)), 3)  # → 0.045

Figure 7 · Chart

−6 −4 −2 0 2 4 6 DPO margin (how strongly the policy already prefers the chosen answer) 0.00 0.02 0.04 0.06 0.08 0.10 update strength β(1 − σ(margin)) DPO pushes hardest on pairs it gets wrong (β = 0.1) worked example: margin 0.2 → 0.045

DPO's push is β for pairs ranked backwards, half that at margin 0, and fades to zero once a pair is learned

Reading it: the x-axis is the margin, how strongly the policy already prefers the chosen answer relative to the reference; the y-axis is how hard one gradient step pushes. On the far left the policy has the pair backwards and gets the full push, β. At zero, with no preference yet, it gets half. On the right the pair is learned and the push fades towards zero, so training spends its effort on the pairs it still gets wrong.

Figure 8 · Chart

0 25 50 75 100 125 150 175 200 training step 0.0 0.2 0.4 0.6 0.8 1.0 policy probability DPO on three candidate answers helpful and correct rude correct but rambling

The helpful answer climbs towards 1 while rude falls fastest and rambling falls more slowly, staying above rude

Reading it: a toy policy for one prompt starts even across three answers (1/3 each). The preferences say "helpful and correct" beats both others, and "correct but rambling" beats "rude". As training runs (x-axis), probability (y-axis) flows to the helpful answer. Rude is pushed down fastest; rambling falls more slowly (0.166 at step 50, 0.005 by step 200) and stays above rude the whole way, the order people expressed. Nothing stops the top answer taking nearly everything, because every pair it appears in keeps pushing it up.

In code: dpo_loss and dpo_update_strength give the loss and the push in the first chart, and train_toy_dpo trains the policy in the second. View source

The judge need not be a person. Constitutional AI and other AI-feedback methods scale up the labelling by having a model compare the responses against written principles. Whoever judges, this stage is where an assistant's tone, helpfulness, refusals and safety behaviour mostly come from.

Start with the reward model of RLHF. Drag its two scores and watch their gap become the chance that the chosen answer wins.

Then DPO. Move the pair's log-probabilities and β and watch how hard one training step pushes, then train a policy that can give only three answers.

Chapter 4

LoRA: low-rank adapters

Pretraining, SFT and preference tuning are run by the model's vendor. The last box in the pipeline is yours: adapting a finished model to your own task. Retraining every weight would mean a full copy of the model for each task. LoRA (low-rank adaptation) leaves the pretrained weights frozen and trains a small adapter beside each layer it changes: two thin matrices, A and B. A squeezes the layer's input down to r numbers, where r, the rank, is far smaller than the layer's width; B expands them back into a correction that is added to the layer's output. Think of sticky notes on a textbook: the book stays as printed, the notes are cheap to write, store and swap, and when you are done you can copy them into the book.

Take a layer whose frozen weights W are the 2×2 identity, so W copies its input, and an adapter with A = (0, 1) as a row and B = (1, 0) as a column. For the input x = (1, 2), the frozen path gives W·x = (1, 2). The adapter squeezes x to one number, A·x = 2, then expands it back, B·2 = (2, 0). The output is (1, 2) + (2, 0) = (3, 2). Two small vectors changed what the layer does, and W is untouched.

Figure 9 · Diagram

Reading it: the input takes two paths. The top path is the pretrained layer, which never changes. The bottom path is the adapter: A squeezes the d numbers of the input down to r (say 8), and B expands them back. B starts at zero, so at first the bottom path adds nothing and the model starts where pretraining left it. Only A and B are trained. Afterwards B·A can be added into W once (merging the adapter), and the model is served at its original speed.
The formula and its symbols

Symbols

Symbol Meaning here Shape / range
input row vector (d_in,)
frozen pretrained weight matrix (d_out, d_in)
transpose: flip rows and columns so the shapes line up for multiplication
trainable "down" matrix, random at start (r, d_in)
trainable "up" matrix, zero at start (d_out, r)
the rank: the width of the bottleneck usually 4 to 64
alpha, a scale knob; α/r keeps update size steady when you change r often r or 2r

In words: the output is what the frozen layer produces plus a scaled correction that passes through a narrow r-number bottleneck.

On the worked example: W = I, A = (0, 1), B = (1, 0)ᵀ, α/r = 1, x = (1, 2): xWᵀ = (1, 2), xAᵀ = 2, 2·Bᵀ = (2, 0), y = (3, 2).

In Python
# x Mᵀ: the dot product of x with each row of M
def times_transpose(x, M):
    return [sum(x_k * m_k for x_k, m_k in zip(x, row)) for row in M]
# frozen, d_out × d_in
W = [[1, 0], [0, 1]]
# r × d_in, with r = 1
A = [[0, 1]]
# d_out × r
B = [[1], [0]]
x, alpha_over_r = [1, 2], 1
# x Wᵀ
frozen = times_transpose(x, W)
# x Aᵀ: squeezed to r numbers
squeezed = times_transpose(x, A)
# (x Aᵀ) Bᵀ: expanded back
correction = times_transpose(squeezed, B)
frozen, squeezed, correction  # → ([1, 2], [2], [2, 0])
# y
[f_j + alpha_over_r * c_j for f_j, c_j in zip(frozen, correction)]  # → [3, 2]
d_in = d_out = 4096
# full, then LoRA at each rank
d_out * d_in, [r * d_in + d_out * r for r in (64, 16, 8)]  # → (16777216, [524288, 131072, 65536])

Parameter savings for one 4096 × 4096 layer:

Method Trainable parameters Share of full
full fine-tune 16,777,216 100%
LoRA r = 64 524,288 3.1%
LoRA r = 16 131,072 0.78%
LoRA r = 8 65,536 0.39%

Figure 10 · Chart

0 50 100 150 200 250 300 training step 1 0 − 8 1 0 − 6 1 0 − 4 1 0 − 2 1 0 0 mean squared error (log scale) The task needs a rank-2 change: rank 1 can't express it rank 1 rank 2 rank 4

A rank-1 adapter plateaus while ranks 2 and 4 drive the error to essentially zero

Reading it: the task is a rank-2 change to a frozen 16 × 16 layer. The x-axis is the training step and the y-axis (log scale) the training error. A rank-1 adapter levels off, because its bottleneck is too narrow to express the change; ranks 2 and 4 drive the error to essentially zero. LoRA rests on this: the change a fine-tune needs has low rank, even though the weights themselves do not.

In code: LoRALinear holds the frozen W beside A and B, and LoRALinear.merged_weight merges them for serving. View source

QLoRA goes further: it stores the frozen base weights in 4 bits (a format called NF4) and trains LoRA adapters in 16-bit on top, which lets a 65-billion-parameter model be fine-tuned on a single 48 GB GPU.

An adapter takes megabytes where the model takes gigabytes, so you can keep one per customer or task and swap them on one shared base model, and training fits on far smaller hardware.

Change the worked example's numbers and watch the layer's output move. Then set a layer's width and the adapter's rank, and count how many numbers each trains.

Chapter 5

Which adaptation should you use?

LoRA is one way to change what a model does, and not the first to try. What fits depends on what is wrong. Fine-tuning changes behaviour; it is a poor way to add knowledge. A model that lacks facts, such as a product catalogue that changes every week, needs retrieval (RAG, retrieval-augmented generation): the system looks the facts up and puts them in the prompt when the question arrives, so they stay current and can be cited. A model that has the facts but gets the format or tone wrong needs its behaviour changed, by the cheapest option that works.

Approach Changes weights? Use when
Prompting / few-shot No behaviour or format change
RAG No knowledge that changes or must be cited
LoRA / QLoRA small adapters style, domain vocabulary, consistent output format
Full fine-tune yes, all rarely: major domain shift with lots of data

Figure 11 · Diagram

Reading it: start at the top. A knowledge problem goes straight to retrieval. A behaviour problem climbs the options in order of cost and stops at the first that works: a better prompt, then a LoRA adapter if the prompt cannot make the behaviour consistent (or is too long and costly to send with every call), and a full fine-tune only for a genuine domain shift with lots of data.

In code: choose_adaptation walks this flowchart and returns where it lands. View source

Answer the flowchart's questions for a problem you have, or press one of the situations, and see where you land.

Chapter 6

Distillation: a small model learns from a big one

The options so far change what a model does; the last one changes what it costs to run. A big model may do a task well but be slow and expensive to serve. Distillation trains a small, cheap student model to imitate a big teacher model. The student learns from the teacher's whole spread of probabilities across the answers, not only its top pick, because the spread says more: which wrong answers the teacher found nearly right, and which it ruled out.

A temperature T brings that information out. Say the teacher's raw scores (logits) for three answers are 2, 1 and 0. Softmax at T = 1 turns them into the probabilities 0.665, 0.245 and 0.090, and the top answer dominates. Dividing the logits by T = 2 first gives softmax(1, 0.5, 0) = 0.506, 0.307, 0.186. The spread is flatter, and the student can see that answer 2 is a much better runner-up than answer 3. What the runner-ups carry is sometimes called "dark knowledge".

Figure 12 · Diagram

Reading it: both models see the same input, and both sets of scores are softened by the same temperature. The KL divergence measures how far the student's spread is from the teacher's, and only the student learns from it; the teacher stays fixed. Run it on the requests your product receives, and the student learns your task.
The formula and its symbols

Symbols

Symbol Meaning here Shape / range
the teacher's logit (raw score) for answer i any real
temperature: divide scores by T before softmax; T > 1 flattens > 0
teacher and student probabilities at temperature T each sums to 1
Kullback-Leibler divergence: the extra surprise from believing q when the truth is p. Zero only when they match ≥ 0
natural logarithm
rescales the gradient, which softening shrinks by 1/T²
mix between matching the teacher and matching the true label 0 … 1
CE ordinary cross-entropy on the true label ≥ 0

In words: the student is penalised by how far its softened spread is from the teacher's, scaled by T², optionally mixed with the usual penalty on the true answer.

On the worked example: with teacher (0.5, 0.5) and student (0.9, 0.1), KL = 0.5·ln(0.5/0.9) + 0.5·ln(0.5/0.1) = −0.294 + 0.805 = 0.511. When the student matches the teacher exactly, KL = 0. If those are the two spreads at T = 2 and α = 1 (learn from the teacher alone), the loss is 2² × 0.511 = 2.04.

In Python
import math
def soft_targets(z, T):
    # e^(z_i / T)
    exps = [math.exp(z_i / T) for z_i in z]
    # divided by Σ_j e^(z_j / T)
    return [e / sum(exps) for e in exps]
[round(p_i, 3) for p_i in soft_targets([2, 1, 0], T=2)]  # → [0.506, 0.307, 0.186]
# teacher, student
p, q = [0.5, 0.5], [0.9, 0.1]
KL = sum(p_i * math.log(p_i / q_i) for p_i, q_i in zip(p, q))
round(KL, 3)  # → 0.511
alpha, T = 1.0, 2
# the (1 − α)·CE term is zero at α = 1
round(alpha * T ** 2 * KL, 2)  # → 2.04

Figure 13 · Chart

T = 1 T = 2 T = 5 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 teacher probability Higher temperature reveals the runner-up ranking answer 1 (logit 2) answer 2 (logit 1) answer 3 (logit 0)

Raising temperature from 1 to 5 flattens the teacher's 0.665, 0.245, 0.090 towards even, revealing the ranking of wrong answers

Reading it: the same three teacher logits (2, 1, 0) at three temperatures. At T = 1 (left group) the top answer dominates. At T = 2 and T = 5 the bars even out, and the order of the wrong answers shows. Raise T too far and every answer flattens towards an even guess, so T is tuned (2 to 5 is common).

In code: distillation_loss combines soft_targets and kl_divergence with the T² scale. View source

A student trained this way for one narrow task can be many times cheaper and faster than its teacher, with little loss of quality on that task.

Turn the temperature up and watch the teacher's runner-up answers appear. Then move the student's scores and watch how far its spread is from the teacher's.

Test yourself

10 questions

Answer each one out loud or on paper before you open it.

Question 1Q: Why does a base model ramble instead of answering?Think it through, then reveal

A: Pretraining only teaches it to continue text. Answering questions in a helpful format is learned later, in SFT and preference tuning.

Question 2Q: What is the one code difference between pretraining loss and SFT loss?Think it through, then reveal

A: A mask. SFT computes the same next-token cross-entropy but averages it only over the reply tokens, so the prompt is read but not trained on.

Question 3Q: In RLHF, what does the reward model learn, and from what?Think it through, then reveal

A: A score for responses such that sigmoid(score gap) predicts which of two responses a labeler preferred. It learns from pairwise comparisons, which are far easier for people to give than perfect answers.

Question 4Q: How does DPO avoid a reward model?Think it through, then reveal

A: It treats the log-probability ratio between the policy and a frozen reference as an implicit reward, and applies the same pairwise loss directly to the policy. One model, one supervised-style training loop.

Question 5Q: What does β control in DPO?Think it through, then reveal

A: How tightly the policy is held to the reference model. It is the weight on the drift penalty in the objective DPO optimises, reward − β × KL(policy ‖ reference), so larger β keeps the policy closer to the reference and smaller β lets the preferences pull it further away. In the loss, a larger β makes each unit of log-ratio count for more, so pairs are satisfied with a smaller departure.

Question 6Q: Why is B initialised to zero in LoRA?Think it through, then reveal

A: So B·A = 0 and the adapted model starts exactly equal to the pretrained model. Training then learns only the change.

Question 7Q: How many parameters does LoRA rank 8 train on a 4096 × 4096 layer?Think it through, then reveal

A: 2 × 4096 × 8 = 65,536, about 0.39% of the 16.8 million in the full matrix.

Question 8Q: Does LoRA slow down inference?Think it through, then reveal

A: Not if you merge: add B·A into W once and serve the result. Unmerged adapters cost two thin extra matmuls, which is what lets you hot-swap adapters on one base model.

Question 9Q: A client wants the model to know their product catalogue, which changes weekly. Fine-tune or RAG?Think it through, then reveal

A: RAG. The knowledge changes and answers should cite sources; fine-tuning would be stale within a week and can't cite. Fine-tune only for behaviour the prompt can't make consistent.

Question 10Q: What does temperature do in distillation?Think it through, then reveal

A: It softens both distributions so the student learns the teacher's relative preferences among wrong answers, not just its top pick; the T² factor keeps gradient sizes comparable.

Primary sources

The papers behind this lesson

Brown et al., Language Models are Few-Shot Learners (GPT-3, 2020): Showed that scaling next-token pretraining produces a model that can follow instructions and examples given only in the prompt.

Read on rumblr →The paper

Kaplan et al., Scaling Laws for Neural Language Models (2020): , with Hoffmann et al., Training Compute-Optimal Large Language Models (2022): Measured how pretraining loss falls predictably with model size, data and compute, and how to balance them.

Read on rumblr →The paper

Ouyang et al., Training language models to follow instructions with human feedback (InstructGPT, 2022): Established the SFT, reward model and RLHF recipe behind chat assistants.

Read on rumblr →The paper

Rafailov et al., Direct Preference Optimization: Your Language Model is Secretly a Reward Model (2023): Showed preference tuning can skip the reward model and RL loop entirely.

Read on rumblr →The paper

Hu et al., LoRA: Low-Rank Adaptation of Large Language Models (2021): , with Dettmers et al., QLoRA (2023): Fine-tuned huge models by training small low-rank adapters beside frozen (and, in QLoRA, 4-bit) weights.

Read on rumblr →The paper

Hinton, Vinyals & Dean, Distilling the Knowledge in a Neural Network (2015): Trained small students on a large teacher's temperature-softened outputs.

Read on rumblr →The paper

Bai et al., Constitutional AI: Harmlessness from AI Feedback (2022): Replaced much human preference labelling with a model judging responses against written principles.

The paper

Researcher's shelf

Further reading

  • Hugging Face PEFT documentation: https://huggingface.co/docs/peft/index
  • Hugging Face TRL documentation (SFT, DPO, reward modelling): https://huggingface.co/docs/trl/index

About this lesson. This is the illustrated edition of a lesson from the open-source AI Primer ↗. Its text, figures and numbers are generated from the Primer's source at commit f8b43d1, so the two always agree: the explanation, the code that builds it and the tests that prove it.