rumblr Work in progressWIP

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

Fine-tuning in practice

preparing data, forgetting old skills, merging models

This lesson covers What a fine-tune costs and risks, and how to prepare data so the language model keeps its old skills

Members · open during launch 54 min22 figures and diagrams9 interactive

What this is

What is fine-tuning?

Fine-tuning is extra training for an AI language model that already works, on your own examples, so that it answers in your format and your style every time. Unlike a prompt or a document lookup, it changes the language model itself. This lesson covers the work around that training run: deciding whether to fine-tune at all, preparing the examples, keeping the skills the language model already had, and merging two fine-tunes into one.

Why it matters: You need it the day no prompt makes a language model behave consistently, or a long prompt sent thousands of times a day becomes most of the bill. With illustrative prices, a $600 fine-tune that cuts a 3,000-token prompt to 300 tokens pays for itself after 125,000 requests.

At a glance

Key takeaways

  1. Decide with an eval: build a held-out set first, try a prompt, then retrieval, and fine-tune only for behaviour no prompt can pin down. The break-even point, in requests, is the fine-tune's one-off cost divided by what it saves on each request.
  2. Data: use the base model's chat template and train only on the assistant's turns; remove near-duplicates; set the held-out set aside before training and remove training examples that nearly copy it; check the labels, because wrong labels cap what the eval can show. Careful examples count for more than many examples.
  3. Forgetting: every weight is shared, so learning a new task erodes old skills, more the further the weights move and the more the tasks conflict. Fewer steps, a lower learning rate and LoRA shorten the trip; only replaying some old data keeps a skill the new task contradicts.
  4. Overfitting: on a small dataset, validation loss bottoms out early; ship the best checkpoint, not the last.
  5. Merging: a task vector is what a fine-tune changed, θ_ft − θ_base. Adding task vectors combines skills with no training; averaging is λ = 1/T, which dilutes each skill; vectors that point in opposite directions cancel.

How it works, from scratch

Picture a skilled cook who joins your restaurant. They can already cook: that is the pretrained model. You want them to cook your menu, your way, and there are three ways to get it. You can hand them a note with every order (a prompt), give them a recipe binder to look things up in (retrieval, RAG), or send them on a course about your kitchen (fine-tuning). Only the course changes the cook.

The course costs the most, so the first question is whether it pays. After that come the ways a course goes wrong: a badly written course book, a cook who loses old dishes while drilling new ones, and a cook who memorises the practice exam instead of learning. The last chapter combines two finished fine-tunes into one model without any more training. The forgetting, the memorising and the merging are all measured on one model small enough to train in a fraction of a second.

Chapter 1

Should you fine-tune at all?

The note, the binder and the course form a ladder, cheapest first. Before trying any of them, build an evaluation set (the eval): a fixed set of examples with known answers, kept out of training, that every option is scored on. Then move down the ladder only when the eval shows that the option above falls short.

Figure 1 · Diagram

Reading it: start at the top, where the first box is the eval, not a model. Each rung is cheaper and faster to change than the one below it. Missing facts go to retrieval, because facts learned by fine-tuning go stale and are hard to update. Wrong behaviour that no prompt can pin down goes to fine-tuning. The last diamond holds the rule: a fine-tune ships only if it beats the prompt on the same eval. Training stages has the same decision as a flowchart of approaches; this one adds the measurement at every step.

Cost can decide the question too. In the kitchen, a note costs a little with every order, and the course costs a lot once. A fine-tune is the same: it costs money once, for the examples and the training run, and then saves a little on every request, because a fine-tuned model needs a much shorter prompt. It pays for itself only after enough requests.

Say a support bot sends a 3,000-token prompt full of instructions and examples on every request, and a fine-tuned model that has learned that behaviour needs only 300 tokens of prompt. Take these illustrative prices (real ones vary by provider and change often): $2 per million input tokens for the general model, and $4 per million for the tuned one, because hosting a custom model usually costs more per token.

Tokens per request Price per million Cost per request
prompted 3,000 $2 3,000 × 2 / 1,000,000 = $0.0060
fine-tuned 300 $4 300 × 4 / 1,000,000 = $0.0012

Each request saves $0.0048. Writing and checking 1,000 training examples plus the training run costs, say, $600 once. After 600 / 0.0048 = 125,000 requests the fine-tune has paid for itself: 25 days at 5,000 requests a day.

The formula and its symbols

Symbols

Symbol Meaning here In the example
"N-star": the break-even number of requests 125,000
one-off cost: writing and checking data, the training run $600
cost of one request
cost of one request with the long prompt, and with the fine-tuned model $0.0060, $0.0012
input tokens sent per request 3,000 and 300
price in dollars per million input tokens $2 and $4
one million: prices are quoted per million tokens

In words: "divide what the fine-tune costs once by what it saves on each request; that is how many requests it takes to earn the cost back."

With the numbers: = 3,000 × 2 / 10⁶ = 0.006, = 300 × 4 / 10⁶ = 0.0012, so = 600 / 0.0048 = 125,000.

In Python
# c = t·p / 1,000,000 for each option
c_prompt = 3000 * 2.0 / 1_000_000
c_tuned = 300 * 4.0 / 1_000_000
c_prompt, c_tuned  # → (0.006, 0.0012)
C_once = 600
# N* = C_once / (c_prompt − c_tuned)
N_star = C_once / (c_prompt - c_tuned)
round(N_star)  # → 125000
# days to break even at 5,000 requests a day
round(N_star / 5000, 1)  # → 25.0

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

Figure 2 · Chart

0 50000 100000 150000 200000 250000 requests served 0 200 400 600 800 1000 1200 1400 total cost so far ($) When does a fine-tune pay for itself? break-even 125,000 requests long prompt: $0.0060 per request fine-tuned: $600 once + $0.0012 per request

The prompted line starts at zero and climbs steeply; the fine-tuned line starts at 600 dollars and climbs slowly; they cross at 125,000 requests

Reading it: the x-axis counts requests served and the y-axis is the total money spent so far. The prompted line starts at zero but climbs steeply, because every request pays for 3,000 tokens. The fine-tuned line starts at $600 (the one-off cost) and climbs slowly. Left of the dashed line, prompting is cheaper; right of it, the fine-tune is. If the tuned model cost as much per request as the prompt, the two lines would never cross, and the only reason left to fine-tune would be quality.

In code: per_request_cost prices one request and break_even_requests returns , or infinity when the tuned model saves nothing per request. View source

Two costs sit outside the formula. Every new base model means repeating the fine-tune, so comes back with each upgrade. And the eval takes engineering time whichever option wins, which is why it is built first.

Set the prompt length, the prices and the traffic to match your own product, and watch where the two cost lines cross.

Chapter 2

Preparing the data

Once a fine-tune is worth trying, the work moves to its examples, the course book. Every example must use the same layout, no example may appear five times, the exam questions must be set aside before the cook sees the book, and the answers must be right. The pipeline below has a step for each. After it comes one more question: how many examples are enough.

Figure 3 · Diagram

Reading it: raw examples enter on the left and pass through each step in turn. Watch the branch at "Set aside the held-out set": the held-out examples leave before anything is trained or tuned, and the next step removes any training example that nearly copies one of them.

2a. Formatting chat examples

A chat model learns from conversations, so each training example is a list of messages, each tagged with who speaks it: the system (standing instructions), the user, or the assistant. The model is trained only on the assistant's lines, the part it will play. Here is one example:

Turn Role Content Trained on?
1 system Be brief. no
2 user Capital of France? no
3 assistant Paris. yes

Rendered into text, it becomes <|system|>Be brief.<|end|><|user|>Capital of France?<|end|><|assistant|>Paris.<|end|>, and only the last segment counts towards the loss.

Figure 4 · Diagram

Reading it: the solid arrows are the order the model reads the turns. The dotted arrows carry no training signal: the system and user turns are context the model conditions on. Only the thick arrow feeds the loss, so the model learns to answer, not to write questions. This is the loss mask of supervised fine-tuning (see Training stages).

Three rules keep the format right. Use the exact chat template the base model was trained with: the role markers above are illustrative, and each model family has its own. Train with the system prompt you will deploy with. And reject any example whose last turn is not the assistant's (there is nothing to learn), whose turns are empty, or whose roles are unknown. A wrong template raises no error: training succeeds, the loss falls, and the deployed model sees markers it never learned, so it behaves like the base model or worse.

In code: chat_example builds the message list, render_chat flattens it into (segment, trained?) pairs, and validate_chat lists every problem with an example. View source

2b. Deduplication

Next, remove repeats. A training set that holds the same example five times trains on it five times as often, and the model starts to parrot it. An exact match misses a reworded copy, so compare texts by their word pairs (two neighbouring words; a window of k words is called a shingle), after lowercasing and dropping punctuation:

Text Word pairs
"How do I reset my password?" how do, do i, i reset, reset my, my password
"how do I reset my password, please" the same 5, plus password please
"How do I change my email?" how do, do i, i change, change my, my email

The first two share 5 of the 6 distinct pairs between them: a near-duplicate. The first and third share 2 of 8: different questions. The share of pairs two texts have in common is their Jaccard similarity:

The formula and its symbols

Symbols

Symbol Meaning here In the example
the sets of word pairs of two texts 5 pairs and 6 pairs
intersection: pairs in both sets 5 shared pairs
union: pairs in either set, each counted once 6 distinct pairs
the number of items in a set
Jaccard similarity, from 0 (nothing shared) to 1 (identical) 0.83

In words: "count the pairs the two texts share, and divide by the number of distinct pairs they have between them."

With the numbers: J = 5 / 6 = 0.83 for the two password questions and 2 / 8 = 0.25 for password against email. A threshold of 0.7 keeps the first password question, drops its rewording, and keeps the email question.

In Python
def pairs(text):
    words = text.lower().replace("?", "").replace(",", "").split()
    return {(a, b) for a, b in zip(words, words[1:])}
A = pairs("How do I reset my password?")
B = pairs("how do I reset my password, please")
C = pairs("How do I change my email?")
# |A ∩ B| and |A ∪ B|
len(A & B), len(A | B)  # → (5, 6)
# J(A, B)
round(len(A & B) / len(A | B), 2)  # → 0.83
# J(A, C)
len(A & C) / len(A | C)  # → 0.25

Figure 5 · Diagram

Reading it: examples arrive one at a time and are compared against everything already kept. A match at or above the threshold is dropped; anything else joins the kept list. The first copy of each group survives, so the order of the data decides which wording you keep.

In code: normalize lowercases and strips punctuation, shingles collects the word pairs, jaccard scores two texts and deduplicate returns the indices worth keeping. View source

Comparing every pair is fine for thousands of examples; at web scale, MinHash estimates the same Jaccard without comparing every pair. Lee et al. found training sets with thousands of near-duplicates, and removing them made models memorise less. Duplicates that cross into the eval do a different kind of harm: a near-copy of an eval question in the training set lets the model recite the answer, and the eval score becomes a memory test.

Try the deduplication test on two questions of your own. Edit either one and watch which word pairs they share.

2c. The held-out set comes first

So the held-out set is made first and then frozen. Chosen any later, it would drift towards whatever the training data happened to cover. Say fifty support questions are deduplicated, shuffled with a fixed seed, and 10 (20%) are set aside. Only then are the other 40 used, and any of the 40 that nearly copies one of the 10 is removed. Every later choice (prompt wording, learning rate, which checkpoint to ship) is scored on those 10. A score on 10 questions, or even 100, is uncertain, and the uncertainty has a size, the margin of error:

The formula and its symbols

Symbols

Symbol Meaning here In the example
the accuracy measured on the held-out set 0.8
the number of held-out examples 100
the standard error: how much the measured accuracy would wobble if you drew a different held-out set of the same size 0.04
how many standard errors to allow; 1.96 covers 95% of the wobble 1.96
margin the true accuracy is probably within ± this of the measured one 0.078

In words: "the measured accuracy is uncertain by about two standard errors, and the standard error shrinks with the square root of the number of examples."

With the numbers: with 100 examples at 80%, the margin is 1.96 × √(0.8 × 0.2 / 100) = 1.96 × 0.04 = 0.078, so "80%" means "somewhere from about 72% to 88%". A fine-tune that scores 83% has not been shown to beat a prompt that scores 80%. With 400 examples the margin halves to 0.039.

In Python
import math
a, n, z = 0.8, 100, 1.96
# the standard error sqrt(a(1 − a)/n)
round(math.sqrt(a * (1 - a) / n), 4)  # → 0.04
# the 95% margin
round(z * math.sqrt(a * (1 - a) / n), 4)  # → 0.0784
# four times as many examples halves it
round(z * math.sqrt(a * (1 - a) / 400), 4)  # → 0.0392

Figure 6 · Diagram

Reading it: the fixed seed makes the split repeatable, so everyone on a team scores against the same held-out set. The held-out branch is frozen the moment it is made. Both branches then meet in the leak check, which only ever removes examples from the training side.

Figure 7 · Chart

1 0 2 1 0 3 held-out examples n (log scale) 2 4 6 8 10 12 14 16 95% margin (percentage points) How precise is an 80% score? Four times the data halves the margin n = 100: ±7.8 n = 400: ±3.9 n = 1600: ±2.0

The margin of error falls from about 16 points at 25 examples to 1.4 points at 3,200; each fourfold increase halves it

Reading it: the x-axis is the number of held-out examples (log scale) and the y-axis is the ± margin, in percentage points, around a measured 80%. The marked points show the square-root law: 100 examples give ±7.8 points, 400 give ±3.9 and 1,600 give ±2.0. Each halving of the margin costs four times the examples, which is why held-out sets of a few hundred are common and a few dozen can only detect big differences.

In code: split_before_training deduplicates, shuffles with a seed, freezes the held-out set and removes leaks with remove_leaks; margin_of_error gives the ± for any accuracy and size. View source

Even a frozen set leaks a little: every time you look at its scores and change something, it seeps into your decisions, so use it sparingly. Overfitting and regularization covers train, validation and test splits, and Evaluation covers building evals.

Set the held-out set's size and the two scores, and see when a fine-tune's win over the prompt is bigger than the margin of error.

2d. Label quality

A held-out set is only as good as its answer key. A key with typos marks a student wrong wherever the key is wrong, and right wherever the student makes the same mistake as the key. Labels do the same to a model. Say a model is truly right 90% of the time, and 10% of the reference labels are wrong. It scores a point when it is right on a right label (0.9 × 0.9 = 0.81), or when it is wrong on a wrong label and the two mistakes cancel (0.1 × 0.1 = 0.01). The eval reports 82%, not 90%.

The formula and its symbols

Symbols

Symbol Meaning here In the example
the model's true accuracy 0.9
epsilon: the share of reference labels that are wrong 0.1
right answer, right label 0.81
wrong answer on a wrong label (yes/no labels only, so the two errors agree) 0.01
what the eval reports 0.82

In words: "the eval gives credit for being right on a correct label, and by accident for being wrong on a wrong one."

With the numbers: 0.9 × 0.9 + 0.1 × 0.1 = 0.82. A perfect model () scores only 1 − ε = 0.9: noisy labels put a ceiling on what the eval can show.

In Python
a, eps = 0.9, 0.1
# right on a right label, plus wrong on a wrong label
round(a * (1 - eps) + (1 - a) * eps, 2)  # → 0.82
# even a perfect model scores only 1 − ε
round(1.0 * (1 - eps), 2)  # → 0.9
# two labelers, five items: how often do they agree?
labeler_1 = ["yes", "no", "yes", "yes", "no"]
labeler_2 = ["yes", "no", "no", "yes", "no"]
sum(p == q for p, q in zip(labeler_1, labeler_2)) / len(labeler_1)  # → 0.8

Figure 8 · Diagram

Reading it: each item takes two coin flips: is the model right, and is the label right? Multiply along a path to get its share. Two paths are scored as right, 0.81 and 0.01, which add up to the 0.82 the eval reports. The 0.09 on the second path is a correct answer marked wrong by a bad label.

To check the labels, have two people label the same sample independently and measure how often they agree. The two labelers in the code above agree on 4 of 5 items, 80%: one item in five is ambiguous or mislabelled, and your eval can't resolve differences smaller than that noise. Read every disagreement; most come from unclear instructions, not careless labelers.

In code: measured_accuracy applies the formula and label_agreement compares two labelers. View source

Wrong training labels do separate damage: the model learns the mistakes, as the small dataset in the overfitting chapter shows with three of them. Care counts for more than volume. Zhou et al. (LIMA) fine-tuned a large model on just 1,000 carefully chosen examples and got a strong assistant.

Set how often the model is right and how many labels are wrong, and read the score the eval reports.

2e. How many examples?

Fewer than you might expect, because fine-tuning teaches a behaviour the base model can almost do already. A few dozen examples show a format, hundreds give a consistent style or a narrow task, and thousands teach a harder specialised skill. Too few has its own cost: the overfitting chapter fine-tunes on 16 examples, and the model soon memorises them, noise included. Labelled data is the expensive part of fine-tuning, so grow it only while it helps:

Figure 9 · Diagram

Reading it: the loop doubles the dataset only while each doubling buys a real improvement, one larger than the held-out set's margin of error. When a doubling stops paying, more of the same data won't help: the fix is better examples or a different approach.

Chapter 3

Catastrophic forgetting

With the data ready, the training run has its own risk: the model can lose skills it already had. Someone who learned to drive in Britain, keeping left, moves to the United States and practises keeping right every day for a month. The new habit wins, and on a trip home they drift to the wrong side of the road, because the new practice rewrote the reflex both rules use. Neural networks do this to an extreme: train on a new task alone and an old one can vanish. This is catastrophic forgetting.

To watch it happen, here is the small model the rest of the lesson uses: a neural network that reads four numbers and answers yes or no, and four tasks for it:

Task Inputs it uses Rule Plays the role of
general all four, anywhere in [−3, 3] yes when x₁ + x₃ > 0 the base model's pretraining
A x₁ in [−3, −1], x₂ in [−2, 2] yes when x₂ > 0 keep left in Britain
B x₁ in [1, 3], x₂ in [−2, 2] yes when x₂ < 0 keep right in the US
C x₃, x₄ in [−2, 2] yes when x₃ + x₄ > 0 an unrelated skill

A and B read the same two inputs and apply opposite rules in different regions, so one model can learn both, but only by paying attention to the region. C reads inputs that A and B never touch.

Figure 10 · Diagram

Reading it: four numbers go in, 16 hidden units each mix all of them, and one output unit turns the hidden units into a probability. Every weight (64 in the first layer, 16 hidden biases, 16 output weights and one output bias) sits in a single vector θ of 97 numbers. Every task flows through the same hidden units, so training on one task can damage another. Neural networks builds this kind of network from scratch.

The base model is this network trained on the general task (99% accuracy on held-out examples). Every fine-tune below starts from it and runs plain gradient descent on 200 examples.

In code: TinyNet is the network, make_task draws each task's examples, base_model trains the base and fine_tune trains a copy of it. View source

3a. The general skill fades while you teach a new one

Fine-tune the base on task A (learning rate 0.5) and check both skills on held-out examples as it trains:

After step Accuracy on A General skill Distance from base
0 (the base) 0.53 0.99 0
5 0.975 0.825 2.60
10 0.995 0.79 2.83
300 0.98 0.655 5.19

Task A is learned in 5 steps. The next 295 steps teach nothing new about A but keep eroding the general skill, from 0.825 to 0.655. The last column shows why: the weights keep travelling away from the base. It measures that distance as the length of the change in every weight:

The formula and its symbols

Symbols

Symbol Meaning here In the example
theta: every weight of the base model, as one vector 97 numbers
every weight after fine-tuning steps
the number of weights 97 (3 in the hand example)
a counter over the weights 1 … P
the -th weight after steps
the length of vector : square each entry, add, take the square root
how far fine-tuning has moved the model 5.19 after 300 steps

In words: "the distance travelled is the length of the change in the weights: square every weight's change, add them up, take the square root."

With the numbers: for a three-weight model moving from (1, 0, 2) to (1.5, −1, 2), the changes are (0.5, −1, 0), and d = √(0.25 + 1 + 0) = √1.25 = 1.118.

In Python
import math
theta_base = [1.0, 0.0, 2.0]
theta_t = [1.5, -1.0, 2.0]
# each weight's change
[t - b for t, b in zip(theta_t, theta_base)]  # → [0.5, -1.0, 0.0]
# ‖θ_t − θ_base‖
round(math.sqrt(sum((t - b) ** 2 for t, b in zip(theta_t, theta_base))), 3)  # → 1.118

Figure 11 · Diagram

Reading it: the gradient from task A's examples moves the shared weights, and both skills read those same weights. The dotted arrow is what is missing: the general skill has no examples in this training run, so nothing pushes back when a change that helps A hurts it.

Figure 12 · Chart

1 0 0 1 0 1 1 0 2 fine-tuning step (log scale) 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 held-out accuracy Learning A, forgetting the general skill task A, lr 0.5 general skill, lr 0.5 task A, lr 0.02 general skill, lr 0.02 0 1 2 3 4 5 distance from the base ‖θ − θ_base‖ 0.65 0.70 0.75 0.80 0.85 0.90 0.95 1.00 general-skill accuracy Forgetting tracks how far the weights move lr 0.5 lr 0.02

Left: accuracy on A jumps to 1 within a few steps while the general skill slides from 0.99 to 0.66 at learning rate 0.5 and only to 0.79 at 0.02. Right: the general skill falls as distance from the base grows

Reading it: on the left, the x-axis is the training step (log scale). Blue lines are accuracy on task A, red lines the general skill; solid is learning rate 0.5, dashed is 0.02. With the big rate, A is learned within a few steps and the general skill then slides for the rest of the run. With the small rate, A is learned later (around step 70) and the general skill ends at 0.79 instead of 0.655, with A just as good. On the right, every step of both runs is plotted as distance from the base against the general skill: the points fall along one downward curve. Forgetting tracks how far the weights move.

So the way to forget less is a shorter trip. Three changes shorten it, and the small model measures two of them:

  • Fewer steps. Stop once the held-out score on the new task stops improving. Here, stopping at step 10 keeps the general skill at 0.79 instead of 0.655, with A at 0.995.
  • A lower learning rate. Smaller steps travel less far for the same result: 0.79 instead of 0.655 after 300 steps.
  • A smaller update. LoRA (see Training stages) freezes the base weights and allows only a low-rank change. Biderman et al. measured this on real language models and summed it up in their title: LoRA learns less and forgets less.

In code: general_skill_run fine-tunes on A and records, after every step, accuracy on A, the general skill and the distance from the base. View source

A fine-tuned assistant can come back worse at everything outside its narrow task. Score the general skills you care about alongside the new task, and prefer the earliest checkpoint that has learned the task.

Run the experiment yourself: fine-tune the base on task A one step at a time, at any of three learning rates, and watch the general skill.

3b. A new task that contradicts an old one

The general skill faded because nothing defended it. A new task that contradicts an old one does more damage. Back to the driver: practising "keep right" pushes directly against "keep left", because both use the same reflex. Take the model fine-tuned on A (98% on A), then fine-tune it for 300 steps on B alone, or on C alone:

Second fine-tune A before A after New task after
on B (contradicts A) 0.98 0.025 1.00
on C (separate inputs) 0.98 0.97 0.98

After B, the model answers A's questions backwards, because it learned "yes when x₂ < 0" everywhere. After C, A is barely touched: C's inputs never flowed through the weights A relies on most. Forgetting is measured as the accuracy the old task lost:

The formula and its symbols

Symbols

Symbol Meaning here In the example
held-out accuracy on the old task before the new fine-tune 0.98
the same, after the new fine-tune 0.025
forgetting: accuracy lost on the old task 0.955

In words: "forgetting is how much accuracy the old task lost."

With the numbers: F = 0.98 − 0.025 = 0.955 after B, and 0.98 − 0.97 = 0.01 after C.

In Python
acc_before, acc_after_B, acc_after_C = 0.98, 0.025, 0.97
# F after the contradicting task B
round(acc_before - acc_after_B, 3)  # → 0.955
# F after task C, on separate inputs
round(acc_before - acc_after_C, 3)  # → 0.01

Figure 13 · Diagram

Reading it: both second fine-tunes start from the same model. The only difference is which weights the new task needs: B needs the very ones A uses, in the opposite direction; C mostly needs others. How much a model forgets depends less on how long you train than on how much the new task overlaps and conflicts with the old one.

Figure 14 · Chart

1 0 0 1 0 1 1 0 2 step of the second fine-tune (log scale) 0.0 0.2 0.4 0.6 0.8 1.0 held-out accuracy Fine-tuning on B after A: A collapses unless replayed accuracy on A (B only) accuracy on B (B only) accuracy on A (B + 10 replayed A) accuracy on B (B + 10 replayed A)

Fine-tuning on B after A: accuracy on A falls from 0.98 to near 0 within a few steps while B rises to 1; with 10 replayed A examples, A dips and then recovers to 0.945

Reading it: the x-axis is the step of the second fine-tune (log scale), the y-axis held-out accuracy. Solid lines are plain fine-tuning on B: B (green) climbs to 1 while A (blue) falls to about half in the same few steps, and A keeps sliding towards zero for as long as training continues. Dashed lines add 10 replayed A examples (replay, below): A still dips at first (to about 0.2 around step 40), then climbs back to 0.945 while B reaches 0.99.

The cures for plain fading only slow this slide. At learning rate 0.02, or stopping after 10 steps, B reaches 0.975 and A still drops to 0.355.

Figure 15 · Chart

0.0 0.2 0.4 0.6 0.8 1.0 accuracy on the new task B 0.0 0.2 0.4 0.6 0.8 1.0 accuracy on the old task A Slower is not safer; replay escapes the trade-off A + B = 1 B only, lr 0.5 B only, lr 0.1 B only, lr 0.02 B + replay, lr 0.5

Accuracy on A against accuracy on B during the second fine-tune: every run on B alone traces the same curve whatever the learning rate and ends near zero on A, while the replay run climbs the right edge to the top-right corner

Reading it: each line traces one run: x is accuracy on B, y is accuracy on A, and each run starts at the top left (knows A, not B). The three learning rates (0.5, 0.1, 0.02) take very different numbers of steps but trace the same curve, close to the dotted line where A + B = 1: every point of B they gain costs about a point of A, and once B is learned, further steps slide A down the right edge towards zero. The replay run (dashed) follows the same curve at first, then climbs the right edge and ends in the top-right corner, knowing both. When the new data contradicts the old skill, slowing down can't help, because nothing in B's data says A still matters.

In code: sequential_run starts from the A fine-tune, trains on a new task (optionally with replay), and records both accuracies at every step; forgetting computes F. View source

Real fine-tunes contradict the base model in ordinary ways: "always answer in JSON" contradicts "chat naturally", and "be terse" contradicts "explain in detail". Expect the old behaviour to vanish wherever your data overrides it, and test for it.

3c. Replay: keep practising the old skill

If nothing in B's data says A still matters, put some of A in. Add just 10 of task A's 200 training examples to B's 200, under 5% of the mix. With them, A ends at 0.945 and B at 0.99, against A 0.025 without replay. So few examples can do this because of how the loss is averaged. Suppose that early in training the model already scores B well (loss 0.05 per example) but has started forgetting A (loss 3.0 on each replayed example):

The formula and its symbols

Symbols

Symbol Meaning here In the example
examples of the new task 200
replayed examples of the old task 10
average loss on the new examples 0.05
average loss on the replayed examples 3.0
the loss training actually minimises: the average over every example in the mix 0.19

In words: "the loss on a mixed dataset is the average over all its examples, so each group counts in proportion to its size times its loss."

With the numbers: (200 × 0.05 + 10 × 3.0) / 210 = (10 + 30) / 210 = 0.19. The 10 replayed examples are under 5% of the data but contribute 0.143 of the 0.19: three quarters of the loss, and so most of the gradient. The old examples carry the most weight at the moment they are being forgotten.

In Python
n_new, L_new = 200, 0.05
n_old, L_old = 10, 3.0
# the replayed share of the data
round(n_old / (n_new + n_old), 3)  # → 0.048
# each group's contribution to the average loss
round(n_new * L_new / 210, 3), round(n_old * L_old / 210, 3)  # → (0.048, 0.143)
# L_mix
round((n_new * L_new + n_old * L_old) / (n_new + n_old), 2)  # → 0.19

Figure 16 · Diagram

Reading it: the old task's small sample joins the new data before training, so every gradient step sees both. This is the counterweight the general skill lacked when the model trained on A alone: when a change that helps B starts hurting A, the replayed examples' loss rises and pushes back.

In code: replay_mix appends the old examples, mixed_loss is the formula, and sequential_run with n_replay=10 runs the experiment. View source

When fine-tuning a language model, mix some general instruction-following data into your task data, so the model stays a good assistant while it learns your task. When you can't replay (the old data is gone or private), methods such as elastic weight consolidation (Kirkpatrick et al.) instead penalise changes to the weights the old task relied on most.

Now the second fine-tune. Start from the model that has learned A, teach it B or C, and choose whether to mix 10 of A's examples back in.

Chapter 4

Overfitting a small dataset

Forgetting can happen on a dataset of any size. A small dataset adds a second risk: the model memorises it. At first, training on a few examples teaches the pattern. Keep going and the model learns every example by heart, mistakes included, and gets worse on new questions. Overfitting and regularization builds this idea from scratch; here it is in a fine-tune.

Fine-tune the base on only 16 examples of task A, 3 of them deliberately mislabelled, for 1,500 epochs. (With full-batch training, one step is one pass over the data, one epoch.)

At the best epoch (71) At the end (1,500 epochs)
training loss 0.373 0.005
validation loss 0.319 1.277

At the best epoch, training loss is higher than validation loss: the model is refusing to fit the three wrong labels, which is what you want. By the end, training loss is nearly zero, so the wrong labels have been memorised, and validation loss has quadrupled.

The formula and its symbols

Symbols

Symbol Meaning here In the example
the epoch 71, then 1,500
average loss on the 16 training examples 0.373, then 0.005
average loss on 200 held-out examples 0.319, then 1.277
the generalisation gap: how much worse the model does on data it hasn't seen −0.054, then 1.272

In words: "the gap is held-out loss minus training loss; a gap that keeps growing means the model is memorising rather than learning."

With the numbers: 0.319 − 0.373 = −0.054 at epoch 71; 1.277 − 0.005 = 1.272 at the end.

In Python
L_train = {"best": 0.373, "end": 0.005}
L_val = {"best": 0.319, "end": 1.277}
# g = L_val − L_train at each point
{t: round(L_val[t] - L_train[t], 3) for t in L_val}  # → {'best': -0.054, 'end': 1.272}

Figure 17 · Chart

1 0 0 1 0 1 1 0 2 1 0 3 epoch (log scale) 0.0 0.5 1.0 1.5 2.0 2.5 loss A small dataset: learning, then memorising best epoch 71 training loss (16 examples, 3 mislabelled) validation loss (200 held-out examples)

Training loss falls steadily to near zero while validation loss bottoms out at epoch 71 and then climbs to four times its best

Reading it: the x-axis is the epoch (log scale), the y-axis the loss. Both curves fall at first while the model learns the real rule. At epoch 71 (the dashed line) validation loss bottoms out; after that the training curve keeps falling as the model memorises the three wrong labels, and the validation curve climbs. The dotted line is where early stopping with a patience of 20 epochs would end the run, keeping the weights from epoch 71.

Figure 18 · Diagram

Reading it: every epoch ends with a checkpoint and a held-out score. The loop keeps going while scores improve or patience remains, and when it stops, the checkpoint that ships is the marked best, not whatever the last epoch left behind.

In code: overfitting_run records both losses at every epoch, and primer.ml.regularization.early_stopping finds the best epoch and the epoch to stop at. View source

Fine-tuning datasets are small next to pretraining data, and big models memorise quickly, so fine-tunes run for only a few epochs. Save a checkpoint every epoch, score each one on the held-out set, and ship the best.

Drag through the same run epoch by epoch, and set the patience: how many epochs without a better validation loss early stopping waits before it ends the run.

Chapter 5

Model merging

So far, each fine-tune has learned one task. Sometimes there are two fine-tunes: two teams fine-tune copies of the same base model, each for its own task, perhaps on data that cannot be pooled. Model merging combines them into one model with no more training, by arithmetic on the weights.

5a. Weight averaging and task arithmetic

Two editors each take a copy of the same draft and make tracked changes: one fixes the grammar, the other tightens the argument. You can apply both sets of changes to the original. If instead you "average" the two edited copies, each change is applied at half strength: half the grammar fixed, half the argument tightened. Weights work the same way. Take a three-weight base (1, 0, 2). One fine-tune moves it to (1.5, 0, 2); another to (1, −1, 2).

Weights Change from the base
base (1, 0, 2)
fine-tune on A (1.5, 0, 2) τ_A = (0.5, 0, 0)
fine-tune on C (1, −1, 2) τ_C = (0, −1, 0)
base + τ_A + τ_C (1.5, −1, 2) both changes in full
average of the two fine-tunes (1.25, −0.5, 2) both changes at half strength

The change a fine-tune made, θ_ft − θ_base, is its task vector. Adding task vectors to the base is task arithmetic.

The formula and its symbols

Symbols

Symbol Meaning here In the example
which task: a counter over the fine-tunes A, C
how many fine-tunes are merged 2
all the weights of the model fine-tuned on task (1.5, 0, 2)
the weights they all started from (1, 0, 2)
tau: task 's task vector, everything its fine-tune changed (0.5, 0, 0)
add up the task vectors τ_A + τ_C = (0.5, −1, 0)
lambda: how strongly to apply the combined changes 1
the merged model's weights (1.5, −1, 2)

In words: "each task vector is what its fine-tune changed; add the changes up, scale them by λ, and apply them to the base."

With the numbers: θ_merged = (1, 0, 2) + 1 × (0.5, −1, 0) = (1.5, −1, 2). With λ = 1/2: (1, 0, 2) + 0.5 × (0.5, −1, 0) = (1.25, −0.5, 2), which is the average of the two fine-tunes. Averaging T fine-tunes is task arithmetic with λ = 1/T.

In Python
theta_base = [1.0, 0.0, 2.0]
theta_A = [1.5, 0.0, 2.0]
theta_C = [1.0, -1.0, 2.0]
# τ_t = θ_t − θ_base
tau_A = [a - b for a, b in zip(theta_A, theta_base)]
tau_C = [c - b for c, b in zip(theta_C, theta_base)]
tau_A, tau_C  # → ([0.5, 0.0, 0.0], [0.0, -1.0, 0.0])
# θ_merged at λ = 1
[b + 1.0 * (a + c) for b, a, c in zip(theta_base, tau_A, tau_C)]  # → [1.5, -1.0, 2.0]
# λ = 1/2 ...
[b + 0.5 * (a + c) for b, a, c in zip(theta_base, tau_A, tau_C)]  # → [1.25, -0.5, 2.0]
# ... is the plain average of the two fine-tunes
[(a + c) / 2 for a, c in zip(theta_A, theta_C)]  # → [1.25, -0.5, 2.0]

Figure 19 · Diagram

Reading it: both fine-tunes start from the same base; that shared start is what makes their changes comparable. Subtracting the base turns each fine-tuned model into a task vector, the arrows are added and scaled, and the result is added back to the base. No data and no gradient steps are involved, and the merged model is the same size and speed as the base.

Figure 20 · Chart

0.0 0.2 0.4 0.6 0.8 1.0 1.2 1.4 λ: strength of the summed task vectors 0.0 0.2 0.4 0.6 0.8 1.0 held-out accuracy of the merge base + λ(τ_A + τ_C): cosine(τ_A, τ_C) = -0.04 plain average (λ = 1/2) accuracy on A accuracy on C

Merging the fine-tunes on A and C: at lambda 1 the merged model scores 0.97 on both, while plain averaging (lambda one half) scores only 0.635 on A

Reading it: the x-axis is λ and the y-axis held-out accuracy of the merged model on A (blue) and on C (green); the dotted line is 0.5, a coin flip. At λ = 1/2, which is plain averaging, each skill is diluted: 0.635 on A. Around λ = 1 the merged model does both tasks at 0.97, as well as either specialist on its own task. Push λ further and the changes overshoot. Their task vectors are nearly perpendicular (cosine −0.04), so adding one barely disturbs the other.

In code: task_vector subtracts the base, merge adds scaled task vectors back, and merge_run merges two fine-tunes at several λ and scores the result. View source

Averaging has a use of its own: averaging several fine-tunes of the same task ("model soups", Wortsman et al.) often beats the best single one. And task vectors can be subtracted as well as added: Ilharco et al. negated a task vector learned from toxic text to make a model less toxic.

5b. Interference: when task vectors collide

Adding works while the two editors change different sentences. If they rewrite the same sentence in opposite directions, one making it warmer and one colder, applying both sets of changes gives a sentence neither intended. Task vectors collide the same way. Take the three-weight changes again, plus a new one: τ_A = (0.5, 0, 0), τ_C = (0, −1, 0) and τ_B = (−0.4, 0, 0.3). τ_A and τ_C touch different weights, so they do not conflict. τ_B pulls the first weight the other way from τ_A. The cosine measures how aligned two changes are:

The formula and its symbols

Symbols

Symbol Meaning here In the example
dot product: multiply matching entries, then add 0.5 × (−0.4) = −0.2
a vector's length 0.5 and 0.5
the cosine of the angle between the two changes: 1 same direction, 0 unrelated, −1 opposite −0.8

In words: "multiply the changes weight by weight and add, then divide by both lengths, so only the direction counts."

With the numbers: τ_A · τ_B = 0.5 × (−0.4) + 0 + 0 = −0.2; ‖τ_A‖ = 0.5, ‖τ_B‖ = √(0.16 + 0.09) = 0.5; cos = −0.2 / 0.25 = −0.8: strongly opposed. cos(τ_A, τ_C) = 0: independent. See Similarity for the cosine from scratch.

In Python
import math
tau_A = [0.5, 0.0, 0.0]
tau_B = [-0.4, 0.0, 0.3]
tau_C = [0.0, -1.0, 0.0]
def cos(u, v):
    dot = sum(a * b for a, b in zip(u, v))
    return dot / (math.sqrt(sum(a * a for a in u)) * math.sqrt(sum(b * b for b in v)))
# opposed changes
round(cos(tau_A, tau_B), 2)  # → -0.8
# changes to different weights
cos(tau_A, tau_C)  # → 0.0

In the small network, the fine-tunes on A and on B (which reverses A's rule) have task vectors with cosine −0.25, against −0.04 for A and C. Each fine-tune learned its rule everywhere, not just in its own region, so the two vectors rewrite the same weights in opposite directions.

Figure 21 · Chart

0.0 0.2 0.4 0.6 0.8 1.0 1.2 1.4 λ: strength of the summed task vectors 0.0 0.2 0.4 0.6 0.8 1.0 held-out accuracy of the merge base + λ(τ_A + τ_B): cosine(τ_A, τ_B) = -0.25 plain average (λ = 1/2) accuracy on A accuracy on B

Merging the fine-tunes on A and B: at every lambda at least one task stays at or below a coin flip, and the best the merge manages on both at once is 0.525

Reading it: the same axes as the previous figure, now merging A with B. No value of λ lifts both lines: wherever one task improves, the other sits near or below a coin flip, and from λ = 1 on both stay there, because the two changes cancel. A model can do both tasks (replay got 0.945 and 0.99), but this merge can't reach it: that model needs to tell the regions apart, and neither fine-tune learned to.

Figure 22 · Diagram

Reading it: start at the cosine between the task vectors, a check that costs nothing. Near zero, the changes live in different weights and adding them usually works. Clearly negative, they fight: train on both datasets together if you can; if you can't, conflict-resolving merges such as TIES-merging (Yadav et al.) drop each task's smallest changes and, for each weight, keep only the changes that agree with the majority sign. Every path ends at the same box: score the merge on every task's held-out set.

In code: cosine measures the angle between two task vectors, and merge_run reports it alongside the merged accuracies. View source

A merge is free to try, and that makes it tempting to trust. It can still lose a skill both of its parents had, so it is scored like any new model.

Try the arithmetic on the three-weight example: move the two fine-tunes, set λ, and watch the task vectors, the merge and the cosine change.

Then the same merge on the small network. Pick two of its fine-tunes, set λ, and see whether one merged model keeps both skills.

Test yourself

9 questions

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

Question 1When is fine-tuning the wrong tool, and what should you try first?Think it through, then reveal

When the model lacks facts, or the facts change: retrieval supplies them and is easy to update. When a clearer prompt with a few examples fixes the behaviour: that is cheaper and survives a base-model upgrade. Fine-tuning earns its cost when behaviour stays inconsistent under the best prompt, or when a long prompt sent millions of times costs more than the fine-tune.

Question 2Why build the held-out set before training, and why check it against the training set?Think it through, then reveal

So that no choice (prompt, learning rate, checkpoint) is made by looking at it, and it stays an honest measure. A training example that nearly copies a held-out one lets the model recite the answer, turning the eval into a memory test; deduplicating across the split prevents it.

Question 3A held-out set has 100 examples and the fine-tune scores 83% against the prompt's 80%. Has it won?Think it through, then reveal

Not yet. At 80% on 100 examples the 95% margin is about ±7.8 points, so a 3-point difference is well inside the noise. You need a larger held-out set (400 examples halve the margin) or a bigger difference.

Question 4If 10% of the eval's labels are wrong, what is the best score a perfect model can get?Think it through, then reveal

90%, because it is marked wrong on every mislabelled item. A 90%-accurate model would score 0.9 × 0.9 + 0.1 × 0.1 = 82%. Noisy labels shrink and blur the differences you are trying to measure.

Question 5What is catastrophic forgetting, and why does it happen?Think it through, then reveal

Training on a new task alone erodes, or wipes out, skills the model had. Every weight is shared between tasks, and only the new task's examples produce gradients, so nothing pushes back when a change that helps the new task hurts an old one. It grows with how far the weights move and with how much the new task conflicts with the old.

Question 6Lowering the learning rate did not stop task A being forgotten. Why not, and what works?Think it through, then reveal

Task B contradicts A on the same inputs, so any progress on B costs A; a lower rate only walks the same trade-off more slowly. Replay works: mixing even 5% of A's examples into B's data gives the model a reason to keep A, and those few examples carry most of the loss exactly when A is slipping.

Question 7Training loss keeps falling, but validation loss has risen since epoch 71. What is happening, and which checkpoint do you ship?Think it through, then reveal

The model has stopped learning the general rule and is memorising the training set, including its mislabelled examples. Ship the checkpoint from epoch 71, the best on the held-out set; early stopping automates exactly this.

Question 8What is a task vector, and why is averaging two fine-tunes the same as task arithmetic with λ = 1/2?Think it through, then reveal

A task vector is everything a fine-tune changed: θ_ft − θ_base. The average of two fine-tunes is (θ_base + τ_1 + θ_base + τ_2) / 2 = θ_base + ½(τ_1 + τ_2), which is task arithmetic with λ = 1/2, so each skill arrives at half strength.

Question 9When does merging fail, and how can you see it coming?Think it through, then reveal

When the task vectors change the same weights in opposite directions, so adding them cancels both skills. A clearly negative cosine between task vectors is the warning; the remedy is joint training or replay, or a conflict-resolving merge such as TIES, and a held-out check on every task either way.

Primary sources

The papers behind this lesson

Ilharco et al., Editing Models with Task Arithmetic (2022)

Defined task vectors as fine-tuned minus pretrained weights and showed that adding them combines skills, and negating them removes a behaviour.

Read on rumblr →The paper
Wortsman et al., Model soups: averaging weights of multiple fine-tuned models improves accuracy without increasing inference time (2022)

Showed that averaging the weights of several fine-tunes of one base often beats the best single fine-tune.

The paper
Yadav et al., TIES-Merging: Resolving Interference When Merging Models (2023)

Traced failed merges to small redundant changes and sign conflicts, and fixed both by trimming and electing a sign per weight.

The paper
Kirkpatrick et al., Overcoming catastrophic forgetting in neural networks (2017)

Introduced elastic weight consolidation, which slows learning on the weights most important to earlier tasks.

The paper
Biderman et al., LoRA Learns Less and Forgets Less (2024)

Measured on real language models that LoRA keeps more of the base model's abilities than full fine-tuning, at the price of learning the new task less completely.

The paper
Zhou et al., LIMA: Less Is More for Alignment (2023)

Fine-tuned a large base model on 1,000 carefully curated examples and got a strong assistant, evidence that example quality matters more than quantity.

Read on rumblr →The paper
Lee et al., Deduplicating Training Data Makes Language Models Better (2021)

Found widespread near-duplicates in standard datasets, including between training and test sets, and showed that removing them reduces memorisation.

The paper

Researcher's shelf

Further reading

  • Goodfellow et al., An Empirical Investigation of Catastrophic Forgetting in Gradient-Based Neural Networks (2013): https://arxiv.org/abs/1312.6211
  • Hu et al., LoRA: Low-Rank Adaptation of Large Language Models (2021): https://arxiv.org/abs/2106.09685
  • Ilharco et al., Editing Models with Task Arithmetic (2022): https://arxiv.org/abs/2212.04089
  • Yadav et al., TIES-Merging (2023): https://arxiv.org/abs/2306.01708
  • Hugging Face TRL, supervised fine-tuning trainer: https://huggingface.co/docs/trl/sft_trainer
  • Hugging Face PEFT, parameter-efficient fine-tuning (LoRA and friends): https://huggingface.co/docs/peft/index
  • mergekit, an open-source toolkit for merging models: https://github.com/arcee-ai/mergekit

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.