Module 10 of 128 lessons

Fine-Tuning and Training

What it takes to change what a model knows or how it behaves, with honest numbers: what fits on your laptop, what needs a rented GPU, and what only a frontier lab can afford.

Course contents · Module 10 of 12
← Build Claude from scratch
98 lessons · 12 modules
  1. 1Understanding Claude and modern AI6
    1. 1.1What is Claude?
    2. 1.2What is an LLM?
    3. 1.3How ChatGPT, Claude, Gemini and other AI assistants work
    4. 1.4AI, machine learning, deep learning, transformers and LLMs
    5. 1.5What happens when you send a message to an AI?
    6. 1.6Tokens, context windows and embeddings
  2. 2Mathematics and foundations6
    1. 2.1Essential linear algebra
    2. 2.2Vectors, matrices and matrix multiplication
    3. 2.3Probability and statistics
    4. 2.4Softmax, gradients and loss functions
    5. 2.5Neural networks and backpropagation
    6. 2.6Practical Python demonstrations
  3. 3Neural network from scratch7
    1. 3.1Set up Python and NumPy
    2. 3.2Build neurons and layers
    3. 3.3Implement forward propagation
    4. 3.4Implement backpropagation
    5. 3.5Implement gradient descent
    6. 3.6Train a small neural network without PyTorch or TensorFlow
    7. 3.7Visualize training and loss
  4. 4Understanding transformers9
    1. 4.1Why traditional RNNs have limitations
    2. 4.2The transformer architecture
    3. 4.3Tokenization and embeddings
    4. 4.4Positional encoding
    5. 4.5Self-attention and multi-head attention
    6. 4.6Query, Key and Value explained visually
    7. 4.7Feed-forward networks
    8. 4.8Layer normalization and residual connections
    9. 4.9Implement a simplified transformer in NumPy
  5. 5Build a GPT-like model9
    1. 5.1Tokenizer implementation
    2. 5.2Vocabulary creation
    3. 5.3Dataset preparation
    4. 5.4Next-token prediction
    5. 5.5Building a decoder-only transformer
    6. 5.6Training a tiny language model
    7. 5.7Text generation and temperature
    8. 5.8Top-k and top-p sampling
    9. 5.9Understanding hallucinations and limitations
  6. 6How Claude is different9
    1. 6.1Claude's architecture at a conceptual level
    2. 6.2Constitutional AI
    3. 6.3Supervised fine-tuning
    4. 6.4Reinforcement learning from human feedback
    5. 6.5Preference optimization
    6. 6.6Safety training and alignment
    7. 6.7System prompts and instruction following
    8. 6.8Long-context processing
    9. 6.9Tool use and agentic behavior
  7. 7Build your own AI assistant10
    1. 7.1Design a Claude-like chat interface
    2. 7.2Conversation management
    3. 7.3System instructions
    4. 7.4Chat history and context management
    5. 7.5Streaming responses
    6. 7.6Markdown and code rendering
    7. 7.7Syntax highlighting
    8. 7.8Error handling
    9. 7.9File upload and document understanding concepts
    10. 7.10Building a frontend chatbot
  8. 8Memory and RAG8
    1. 8.1What is AI memory?
    2. 8.2Short-term vs long-term memory
    3. 8.3Embeddings and vector databases
    4. 8.4Semantic search
    5. 8.5Retrieval-Augmented Generation (RAG)
    6. 8.6Chunking and document retrieval
    7. 8.7Build a basic document Q&A system
    8. 8.8Context injection and source citations
  9. 9Function calling and agents9
    1. 9.1What is function calling?
    2. 9.2Tool definitions and JSON schemas
    3. 9.3Calling external tools
    4. 9.4Tool execution loops
    5. 9.5Search, calculator and other tools
    6. 9.6Multi-step reasoning and planning
    7. 9.7Agent architecture
    8. 9.8Safety restrictions and tool permissions
    9. 9.9Build a basic tool-using AI agent
  10. 10Fine-tuning and training8
    1. 10.1Pretraining vs fine-tuning
    2. 10.2Dataset collection and cleaning
    3. 10.3Instruction datasets
    4. 10.4Fine-tuning concepts
    5. 10.5LoRA and QLoRA
    6. 10.6GPU and VRAM requirements
    7. 10.7Training costs and realistic hardware requirements
    8. 10.8Model evaluation and benchmarking
  11. 11Deployment and production9
    1. 11.1Model inference
    2. 11.2Quantization
    3. 11.3CPU vs GPU inference
    4. 11.4Running open-source LLMs locally
    5. 11.5Ollama and Hugging Face concepts
    6. 11.6API design
    7. 11.7Docker deployment
    8. 11.8Monitoring and logging
    9. 11.9Security, rate limiting and cost optimization
  12. 12Capstone project8
    1. 12.1Capstone overview and architecture
    2. 12.2The conversational UI
    3. 12.3Conversation history and system prompts
    4. 12.4Streaming output with Markdown and code
    5. 12.5Configurable model providers and error handling
    6. 12.6Document Q&A and memory
    7. 12.7Tool calling
    8. 12.8Testing, deployment and the capstone challenge

Lesson 10.1Module 10: Fine-tuning and training

Pretraining vs fine-tuning

  • ⏱ 19 min read
  • Intermediate

Learning objectives

  • Explain what pretraining and fine-tuning each change in a model, and why they differ by several orders of magnitude in data and compute.
  • Place your own fine-tuning on the map: pretraining, post-training by the model's maker, then adaptation by you.
  • Decide when fine-tuning is the right tool and when prompting, retrieval (module 8) or tools (module 9) are better.
  • Run a tiny experiment that compares pretraining, fine-tuning and training from scratch, and read its results honestly.

In module 5 you trained a tiny GPT from random numbers, and in module 6 you saw how a raw language model is turned into an assistant. Both were about building a model. This module is about adapting one: taking a model that already exists and changing what it does with your own data, on hardware you can actually rent or own. The first step is to be precise about two words that are often blurred: pretraining and fine-tuning.

Analogy: a general education, then a residency

A doctor spends many years at school and university learning to read, reason, and absorb biology, chemistry and medicine in general. That is pretraining: long, expensive, broad. Then a few years of residency in one speciality turn the generalist into a cardiologist. That is fine-tuning: short compared with what came before, narrow, and it only works because the general education is already there. Nobody tries to teach cardiology to someone who cannot read. And a residency changes how the doctor works far more than how much general knowledge they have.

What pretraining does

Pretraining is the next-token prediction you implemented in lesson 5.6, at a vastly larger scale. The model starts from random weights and reads a huge, mixed collection of text (web pages, books, code, papers, often in many languages), predicting each next token and nudging its weights after every batch. For frontier models, public estimates put the data at trillions to tens of trillions of tokens and the compute at thousands to tens of thousands of accelerators for weeks to months. The result is a base model: it has absorbed grammar, facts, coding patterns and a surprising amount of reasoning skill, but it only knows how to continue documents. Ask it a question and it may continue with three more questions, as you saw in lesson 6.1.

Almost everything a model "knows" comes from this stage. That is the key fact for the rest of the module: the knowledge is laid down during pretraining, and later stages mostly decide how that knowledge is used.

What fine-tuning does

Fine-tuning means continuing to train an already-trained model on a much smaller, carefully chosen dataset. Mechanically it is the same loop: forward pass, loss, backward pass, optimiser step. What changes is the starting point (trained weights instead of random ones), the data (thousands to millions of examples instead of trillions of tokens), the learning rate (usually much smaller, so you adjust rather than overwrite) and the goal (a behaviour, a format, a domain, a task).

There are two layers of fine-tuning in practice, and it helps to keep them apart:

  • Post-training by the model's maker. Supervised fine-tuning on conversations, preference training and safety training turn a base model into an assistant (module 6). Labs invest heavily in this data. For Claude, Anthropic has publicly described using RLHF and Constitutional AI Public; the exact data, recipe and scale are Not public.
  • Adaptation by you. You take an open-weight model (for example from the Llama, Mistral, Qwen or Gemma families), usually an already instruction-tuned one, and fine-tune it for your task, often with LoRA adapters on a single GPU (lesson 10.5). This is what the rest of the module teaches.
Huge text mix
Web text, books, code, papers and more, filtered and deduplicated (lesson 10.2 shows the cleaning steps on a small scale). Public estimates for frontier models: trillions to tens of trillions of tokens.
Pretraining
Next-token prediction from random weights. By far the largest share of compute; only a few organisations can afford it at frontier scale (lesson 10.7).
Base model
Knows a lot, but only continues text. Some open-weight families publish their base models next to the chat versions.
Post-training
Supervised fine-tuning, preference optimisation, Constitutional AI and safety training (module 6). Much less compute than pretraining, much more careful data.
Instruct / chat model
What you talk to. Open-weight versions can be downloaded and fine-tuned; closed models such as Claude are used through an API.
Your fine-tune
A small extra training run on your own examples, usually with LoRA or QLoRA (lesson 10.5), on one GPU for minutes to hours.
Your model
The original weights plus a small adapter file. Evaluate it against the model you started from before you trust it (lesson 10.8).
Often enough instead
A better system prompt, a few examples in the prompt, retrieval of your documents (module 8) or tools (module 9) need no training at all, and should be tried first.
From raw text to your own adapted model. Each step down the chain is cheaper than the one before it; the "often enough instead" route needs no training at all.
PretrainingFine-tuning (yours)
Starts fromrandom weightsa trained model
Dataraw text, trillions of tokens, mostly unlabelledcurated examples, thousands to millions of tokens, often conversations
Learnslanguage, facts, skillsbehaviour, format, style, a narrow task or domain
Compute (public estimates)frontier: thousands to tens of thousands of accelerators, weeks to monthsone GPU for minutes to hours (LoRA / QLoRA)
Cost (as of 2026, rough)frontier: tens to hundreds of millions of dollarsa few dollars to a few hundred dollars
Main risksa failed multi-million run, data qualityoverfitting, forgetting, a model that is confidently wrong

When to fine-tune, and when not to

Fine-tuning is good at changing how a model behaves. It is a poor way to give a model new facts. That sounds surprising until you remember where knowledge comes from: a few thousand examples cannot compete with trillions of pretraining tokens, and research such as Gekhman et al. (2024, "Does Fine-Tuning LLMs on New Knowledge Encourage Hallucinations?") found that examples introducing unfamiliar facts are learned slowly and make the model more likely to guess confidently. This is why module 6 warned against using fine-tuning to add knowledge.

Good reasons to fine-tune

  • A consistent output format or style that prompting does not hold reliably (a JSON shape, a house tone, short answers).
  • A narrow, repetitive task done millions of times, where a small fine-tuned model replaces a large prompted one and cuts cost and latency.
  • Domain language and conventions (legal drafting, a medical note format, an in-house programming style).
  • Behaviour you can demonstrate with examples but not easily describe.

Better solved another way

  • "The model does not know our product": put the documents in the context with retrieval (module 8).
  • "It needs today's prices": call a tool (module 9).
  • "It ignores my rule": write a clearer system prompt with examples (lesson 6.7).
  • Anything you have fewer than about 50 good examples of: you cannot train it, and you cannot measure it either.

A good default order is: prompt engineering, then few-shot examples in the prompt, then retrieval or tools, then fine-tuning, and only for organisations with very large budgets continued pretraining or pretraining from scratch. Each step costs more and is harder to undo. For closed models like Claude you cannot download the weights at all; you customise them with prompts, tools and retrieval, plus whatever fine-tuning options a provider offers for some models (availability changes, so check the current docs). Use the helper below to practise the decision.

Which approach fits?Interactive

Pick a goal and the resources you have. The suggestion follows the rules of thumb in this lesson; real projects often combine several.

Experiment: pretrain, fine-tune, or start from scratch?

The script below makes the three options concrete with the smallest possible language model: a character bigram model, a table of 51 × 51 logits that predicts the next character from the current one (the first model of lesson 5.4). It is "pretrained" on about 1,100 characters of everyday English, then fine-tuned on 266 characters of Python code. A third copy is trained on the same code from random weights. Each is scored on held-out English and held-out code it never saw.

Simplified implementation Simplified

A bigram table has 2,601 parameters and no context beyond one character; real models have billions of parameters and thousands of tokens of context. The point is the pattern of results, which is the same pattern seen at scale: fine-tuning from a good starting point beats training from scratch on little data, at a tiny fraction of the cost, and it can damage what the model knew before.

# @run
# pretrain_vs_finetune.py: pretraining vs fine-tuning vs training from scratch, on a tiny character bigram model.
# "Pretraining" = many steps on a larger general English text. "Fine-tuning" = a few steps on a small domain
# text (Python code), starting from the pretrained weights. "From scratch" = the same small domain text, random start.
# A bigram model is far simpler than a transformer, but the trade-offs it shows are the same ones.
import numpy as np

GENERAL = (
    "The river was quiet in the early morning, and the town had not woken up yet. A baker opened his shop and "
    "the smell of fresh bread moved slowly along the street. Children would soon walk to school, and their "
    "parents would hurry to the station to catch the first train. Most people in the town knew each other by "
    "name. They talked about the weather, the price of vegetables and the new bridge that the council had "
    "promised for many years. In the evening the square filled with music. Old friends sat at small tables, "
    "drank tea and told the same stories they had told the week before, and nobody minded at all. When the "
    "rain came in autumn, the river rose and the fishermen pulled their boats higher onto the stones. A "
    "teacher wrote a short history of the town and read it aloud in the library, and the room was full. "
    "She explained how the first families had arrived, how they built the mill, and why the market was held "
    "on the same day every week. After the reading, people asked questions and shared memories of their "
    "grandparents. It was late when the last of them walked home under the lamps."
)
GENERAL_VAL = (
    "On Sunday the market was busy. A farmer sold apples and honey, and a young woman played the violin "
    "near the fountain while people listened and smiled. Later the sky turned grey and everyone went home."
)
DOMAIN = (
    "def mean(values):\n    total = 0\n    for v in values:\n        total += v\n    return total / len(values)\n\n"
    "def clamp(x, low, high):\n    if x < low:\n        return low\n    if x > high:\n        return high\n    return x\n\n"
    "for i in range(10):\n    print(i, mean([i, i + 1]))\n"
)
DOMAIN_VAL = (
    "def count_words(text):\n    words = text.split()\n    return len(words)\n\n"
    "def first(items, default=None):\n    for item in items:\n        return item\n    return default\n"
)

chars = sorted(set(GENERAL + GENERAL_VAL + DOMAIN + DOMAIN_VAL))
idx = {c: i for i, c in enumerate(chars)}
V = len(chars)


def counts(text):
    """C[a, b] = how many times character b follows character a."""
    C = np.zeros((V, V))
    for a, b in zip(text, text[1:]):
        C[idx[a], idx[b]] += 1
    return C


def loss(W, C):
    """Average cross-entropy (nats per character) of the bigram logits W on the pairs counted in C."""
    logp = W - np.log(np.exp(W - W.max(1, keepdims=True)).sum(1, keepdims=True)) - W.max(1, keepdims=True)
    return float(-(C * logp).sum() / C.sum())


def train(W, C, steps, lr):
    """Full-batch gradient descent on the cross-entropy. Returns new weights (W is not modified)."""
    W = W.copy()
    n = C.sum()
    for _ in range(steps):
        P = np.exp(W - W.max(1, keepdims=True))
        P /= P.sum(1, keepdims=True)
        grad = (C.sum(1, keepdims=True) * P - C) / n      # d loss / d logits, for every row at once
        W -= lr * grad
    return W


C_gen, C_gen_val = counts(GENERAL), counts(GENERAL_VAL)
C_dom, C_dom_val = counts(DOMAIN), counts(DOMAIN_VAL)
print(f"vocabulary: {V} characters, so {V * V:,} parameters (one logit per character pair)")
print(f"general text: {len(GENERAL):,} characters; domain (code) text: {len(DOMAIN)} characters\n")

rng = np.random.default_rng(0)
W_init = rng.normal(0, 0.01, size=(V, V))
PRE_STEPS, FT_STEPS, LR = 3000, 150, 20.0

W_pre = train(W_init, C_gen, PRE_STEPS, LR)                  # 1. pretraining on general text
W_ft = train(W_pre, C_dom, FT_STEPS, LR)                     # 2. fine-tuning: start from W_pre
W_scratch = train(W_init, C_dom, FT_STEPS, LR)               # 3. same small data and steps, random start

print(f"{'model':<26}{'general val':>12}{'code val':>10}")
print(f"{'uniform guess':<26}{np.log(V):>12.3f}{np.log(V):>10.3f}")
for name, W in [("pretrained only", W_pre), ("from scratch on code", W_scratch),
                ("pretrained + fine-tuned", W_ft)]:
    print(f"{name:<26}{loss(W, C_gen_val):>12.3f}{loss(W, C_dom_val):>10.3f}")

pre_work = PRE_STEPS * (len(GENERAL) - 1)
ft_work = FT_STEPS * (len(DOMAIN) - 1)
print(f"\ncharacter-steps of work: pretraining {pre_work:,}, fine-tuning {ft_work:,} "
      f"({100 * ft_work / pre_work:.1f}% of pretraining)")

# What did fine-tuning change? Compare next-character predictions after a newline.
def top3(W, ch):
    p = np.exp(W[idx[ch]] - W[idx[ch]].max())
    p /= p.sum()
    best = np.argsort(-p)[:3]
    return ", ".join(f"{chars[i]!r} {p[i]:.2f}" for i in best)

for name, W in [("pretrained", W_pre), ("fine-tuned", W_ft)]:
    print(f"after '\\n' the {name:<10} model predicts: {top3(W, chr(10))}")
  1. GENERAL, DOMAIN and their _VAL twins: the pretraining text, the fine-tuning text and two held-out texts used only for scoring. Never score on the text you trained on.
  2. counts(text): a bigram model only needs to know how often each character follows each other one, so the whole dataset collapses into a 51 × 51 count matrix. This makes full-batch training very fast.
  3. loss(W, C): the average cross-entropy in nats per character, computed with the max-subtraction trick from lesson 2.4 so the exponentials cannot overflow. A uniform guess scores ln51≈3.93.
  4. train(W, C, steps, lr): gradient descent. The gradient of cross-entropy with respect to the logits is "predicted probability minus observed frequency", the same rule as in lesson 2.4, applied to every row at once.
  5. W_pre = train(W_init, C_gen, 3000, 20.0): pretraining, the long run on general text.
  6. W_ft = train(W_pre, C_dom, 150, 20.0): fine-tuning. The only difference from the next line is the starting point.
  7. W_scratch = train(W_init, C_dom, 150, 20.0): same data, same steps, random start.
  8. The last block counts the work done (steps × characters) and shows what the model expects after a newline before and after fine-tuning.
vocabulary: 51 characters, so 2,601 parameters (one logit per character pair)
general text: 1,093 characters; domain (code) text: 266 characters

model                      general val  code val
uniform guess                    3.932     3.932
pretrained only                  2.584     4.730
from scratch on code             5.499     3.669
pretrained + fine-tuned          4.693     3.578

character-steps of work: pretraining 3,276,000, fine-tuning 39,750 (1.2% of pretraining)
after '\n' the pretrained model predicts: 'v' 0.02, 'w' 0.02, 'p' 0.02
after '\n' the fine-tuned model predicts: ' ' 0.71, '\n' 0.14, 'f' 0.06

Read the table column by column:

  • Code. The pretrained model is worse than a uniform guess on code (4.730 > 3.932): it has learned that English almost never puts four spaces after a newline, so code surprises it. Fine-tuning fixes that (3.578) and beats the from-scratch model (3.669), because it starts from sensible English letter statistics that also appear in identifiers like count_words.
  • Cost. Fine-tuning used 1.2% of the work of pretraining. At real scale the ratio is often far smaller.
  • English. After fine-tuning, the model got much worse at English (2.584 → 4.693). This is catastrophic forgetting, the main risk of fine-tuning. It is still better than the from-scratch model (5.499) because not everything was overwritten. Lesson 10.4 measures it properly and shows two cures: smaller learning rates or fewer steps, and mixing some general data back in.
  • After a newline, the fine-tuned model now expects spaces (indentation) with 71% probability: it has learned a format, which is exactly what fine-tuning is good at.
Continued pretraining, distillation, and why so little data is enough

Continued pretraining (also called domain-adaptive pretraining) sits between the two: you keep training a base model with the plain next-token objective on a large amount of raw domain text (for example hundreds of millions of tokens of legal or biomedical documents), and only then do instruction fine-tuning. Gururangan et al. (2020, "Don't Stop Pretraining") showed gains from this on several domains. It needs far more data and compute than instruction fine-tuning, and it is the one way that does add a lot of domain knowledge, at the price of forgetting if you do not mix general text back in Industry practice.

Distillation trains a small model to imitate a large one, either on the large model's generated answers (sequence-level) or on its full output probabilities (logit-level). Many small open models are trained partly this way. If you generate training data with a commercial API, read its terms: several providers restrict using outputs to build competing models.

Why does a few thousand examples change a model with billions of parameters at all? Aghajanyan et al. (2020, "Intrinsic Dimensionality Explains the Effectiveness of Language Model Fine-Tuning") found that fine-tuning can reach most of its benefit while moving the weights only within a surprisingly low-dimensional subspace, and the larger the pretrained model, the smaller that subspace. That observation is the direct motivation for LoRA (lesson 10.5). The LIMA paper (Zhou et al., 2023) pushed the idea further: 1,000 carefully chosen conversations were enough to give a strong base model a good assistant style, which the authors summarised as a "superficial alignment hypothesis". Treat it as a hypothesis about style and format, not a claim that 1,000 examples teach safety or deep skills.

Base or instruct model as your starting point? Fine-tuning an instruct model keeps its chat behaviour and safety training and needs fewer examples; fine-tuning a base model gives you more control but you must teach everything about the conversation format yourself. For most projects, start from the instruct model and its own chat template (lesson 10.3).

Common mistakes and debugging tips

Fine-tuning to teach facts

A team fine-tunes on its product manual and the model still invents features, now with more confidence and in the house style.

Fix: facts belong in the context (retrieval, module 8) where they can be updated and cited. Fine-tune for behaviour: how to use retrieved documents, the tone, the format, when to say "I don't know".

Skipping the cheap baseline

Weeks go into a dataset and a training run, and nobody checked whether a better system prompt with three examples already solved the problem.

Fix: before any training, build the evaluation set (lesson 10.8) and score a prompted baseline. Fine-tune only if the gap is real and the baseline cannot close it.

Scoring on the training text

In the script, the fine-tuned model scores 1.6 nats on its own training code but 3.6 on unseen code. Reporting the first number would hide overfitting completely.

Fix: split off validation and test data before training, and never look at the test set while making decisions.

Ignoring the licence

Open-weight models come with licences that differ: some allow any use, some restrict commercial use above a size, some require attribution or forbid certain uses.

Fix: read the model card and licence on the model's page (for example on huggingface.co) before you invest in a fine-tune, and keep a note of it next to your adapter.

Key takeaways

  • Pretraining builds knowledge from trillions of tokens; fine-tuning adjusts behaviour from thousands of examples, starting from trained weights.
  • Fine-tuning a good starting point beats training from scratch on little data, at a tiny fraction of the cost, but it can make the model forget.
  • Try prompting, retrieval and tools first; fine-tune for format, style, narrow tasks and cost, not to add facts.
  • Claude's training recipe is not public beyond the published methods; your own fine-tuning happens on open-weight models.

Exercise: fewer steps, and a different domain

1) In pretrain_vs_finetune.py, change FT_STEPS to 50 and run again. What happens to the code score and the English score? 2) Replace DOMAIN and DOMAIN_VAL with short texts of your own (for example song lyrics or SQL queries) and check whether fine-tuning still beats training from scratch. 3) For each of these requests, write one sentence choosing an approach: "answer from our 400-page HR policy", "always output a valid invoice JSON", "classify 50 million support emails per month into 12 categories".

Hint

Every character in your new texts must be in the vocabulary, and it is built from all four texts automatically. For part 3, ask: is it knowledge, live data, format, or volume?

Show a solution

1) With 50 steps the fine-tuned model scores about 3.19 on code (better than with 150 steps) and about 3.81 on English (less forgetting). 150 steps was already overfitting the 266 characters; lesson 10.4 finds the best stopping point automatically.

2) For most texts fine-tuning still wins on the domain validation set; the gap may shrink when the domain shares few character pairs with English (try text in another alphabet: the pretrained model then has nothing useful to transfer).

3) HR policy: retrieval (knowledge that changes and needs citations). Invoice JSON: structured outputs or strict tool use first (lesson 9.2), fine-tuning only if that is not available. 50 million emails: a strong case for fine-tuning a small open model (or even a classifier) on a few thousand labelled emails, after measuring a prompted large model as the baseline.

Check your understanding

Where does most of an LLM's factual knowledge come from?

  1. Supervised fine-tuning on conversations
  2. Pretraining on a very large text corpus
  3. The system prompt
Pretraining sees trillions of tokens; fine-tuning datasets are tiny by comparison and mostly shape behaviour. The system prompt only adds what fits in the context for that request.

In the experiment, why did the fine-tuned model beat the model trained from scratch on held-out code?

  1. It trained for more steps
  2. It saw the validation code during fine-tuning
  3. It started from weights that already knew useful English letter patterns
Both runs used the same data and 150 steps; neither saw the validation text. The only difference is the starting point, and transferring what was learned before is the whole value of fine-tuning.

A support bot must quote the current refund policy, which changes every quarter. What should you do first?

  1. Retrieve the current policy into the context and ask the model to quote it
  2. Fine-tune the model on the policy every quarter
  3. Pretrain a new model that includes the policy
Changing facts belong in the context, where they are updated instantly and can be cited. Fine-tuning on them is slow, costly, hard to undo and tends to produce confident paraphrases rather than exact quotes.

Lesson 10.2Module 10: Fine-tuning and training

Dataset collection and cleaning

  • ⏱ 20 min read
  • Intermediate

Learning objectives

  • List the main sources of fine-tuning data and the legal, privacy and quality questions each raises.
  • Build a cleaning pipeline: normalisation, PII redaction, quality and language filters, toxicity filtering, exact and near-duplicate removal, decontamination.
  • Explain how MinHash and locality-sensitive hashing find near-duplicates without comparing every pair.
  • Know which steps change at pretraining scale and why data work, not model code, decides most results.

Practitioners repeat one sentence so often it has become a cliché, because it keeps being true: the data matters more than the model code. Two teams with the same open model, the same LoRA settings and the same GPU get very different results, and the difference is almost always in what they trained on. This lesson is about getting the raw material right before any training happens.

Analogy: washing vegetables before cooking

A chef can follow a perfect recipe and still serve a bad meal if the vegetables are muddy, half are rotten and a few belong to a different dish. So before cooking there is a dull, essential routine: wash, sort, throw out what is spoiled, remove duplicates of the same batch, and keep the ingredients reserved for the tasting panel away from the pot. A model "eats" whatever you feed it, including the mud, and it repeats what it ate most often.

Where fine-tuning data comes from

SourceStrengthsWatch out for
Your own logs (support tickets, chats, emails)exactly your domain and your users' languageconsent and privacy policy, personal data, answers that were wrong or rude, sensitive customer details
Your documents (manuals, wikis, code)accurate, approved contentit is knowledge, not conversations: usually better used through retrieval (module 8); turn it into question-answer pairs only for style
Expert-written exampleshighest quality per exampleslow and expensive; write guidelines so experts are consistent
Public datasets (for example on huggingface.co)free, large, variedlicences differ per dataset, quality varies, many popular test sets have leaked into them
Synthetic data generated by a stronger modelcheap and fast to scale; easy to cover rare casesprovider terms of service, repeated phrasing, invented facts, the generator's own mistakes and biases

Whatever the source, write down for each record where it came from, under which licence or permission, and when. This provenance lets you remove a source later (a customer withdraws consent, a dataset's licence turns out to be wrong) without starting over. A short "datasheet" describing the dataset, its purpose, its known gaps and its cleaning steps is good practice Industry practice.

The cleaning pipeline

Raw data passes through a sequence of filters. The order matters: cheap checks first, expensive ones later, and the comparison with the test set last, on what remains.

  1. Normalise first, so that later checks are not fooled by invisible differences: two kinds of space, a full-width letter or a different Unicode form of "é".
  2. Redact personal data before anything else is stored or shown to reviewers.
  3. Cheap heuristic filters remove fragments, symbol soup, keyword spam, the wrong language and abuse.
  4. Remove exact copies with a hash, then near-copies with MinHash and LSH.
  5. Drop anything that overlaps the evaluation data, then save a versioned dataset and read a random sample yourself.
The pipeline implemented in clean_data.py. Each stage logs what it dropped and why.

A miniature pipeline you can run

The script cleans 14 short documents that contain one of each typical problem: a whitespace variant of a document, a reworded near-copy, personal data, a fragment, symbol spam, a repeated word, Spanish text, an insult, and a maths question that also appears in the test set. It uses only the standard library.

# @run
# clean_data.py: a miniature data-cleaning pipeline for fine-tuning (or pre-training) text.
# normalise -> redact PII -> quality filters -> language check -> toxicity blocklist
# -> exact dedup -> near-duplicate removal (MinHash + LSH) -> decontamination against a test set.
# Standard library only. Real pipelines use the same ideas at a much larger scale.
import hashlib
import re
import unicodedata
import zlib

RAW = [
    "How do I reset my password? Go to Settings > Security and click Reset password. You will get an email within five minutes.",
    "How do I reset my password?   Go to Settings > Security and click Reset password.  You will get an email within five minutes.",
    "How can I reset my password? Go to Settings > Security and click Reset password. You will receive an email within five minutes.",
    "If the export still fails after the update, contact me at jane.doe@example.com or +1 415 555 0134 and I will look at the logs.",
    "click here!!!",
    "$$$ BUY NOW $$$ !!! >>> http://spam.example <<< $$$ 100% FREE $$$",
    "free free free free free free free free free free free free",
    "Cómo restablezco mi contraseña? Ve a Configuración, pulsa Restablecer y revisa tu correo.",
    "You are an idiot for asking this, just read the manual like everyone else.",
    "Invoices can be downloaded as PDF from Billing > History. Each invoice lists the plan, the period and the tax applied.",
    "To export your data, open Settings > Data and choose Export. Large exports are emailed to you as a zip file.",
    "Q: A train travels 60 km in 1.5 hours. What is its average speed in km per hour? A: 40 km/h.",
    "Two-factor authentication adds a second step when you log in. You can use an authenticator app or SMS codes.",
    "To export your data, open Settings > Data and choose Export. Large exports are sent to you by email as a zip file.",
]

# Items from an evaluation set. Nothing that overlaps them may stay in the training data.
TEST_SET = [
    "A train travels 60 km in 1.5 hours. What is its average speed in km per hour?",
    "What is the capital of Australia?",
]

ENGLISH_WORDS = set("the and to of is in it you your for on with as are be can this that if or from by at an "
                    "do how what when will i we my me not get each".split())
BLOCKLIST = {"idiot", "stupid", "moron"}          # toy stand-in for a toxicity classifier


def normalise(text):
    text = unicodedata.normalize("NFKC", text)     # unify look-alike Unicode characters
    return re.sub(r"\s+", " ", text).strip()       # collapse runs of whitespace


EMAIL = re.compile(r"[\w.+-]+@[\w-]+(?:\.[\w-]+)+")
PHONE = re.compile(r"\+?\d[\d ()-]{7,}\d")


def redact_pii(text):
    text = EMAIL.sub("<EMAIL>", text)
    return PHONE.sub("<PHONE>", text)


def words(text):
    return re.findall(r"[^\W\d_]+", text.lower())   # letters only (handles accents)


def quality_problem(text):
    w = words(text)
    if len(w) < 6:
        return "too short"
    chars = [c for c in text if not c.isspace()]
    if sum(c.isalpha() for c in chars) / len(chars) < 0.6:
        return "mostly symbols"
    top = max(w.count(x) for x in set(w))
    if top / len(w) > 0.3:
        return "repetitive"
    return None


def looks_english(text):
    w = words(text)
    return sum(x in ENGLISH_WORDS for x in w) / len(w) >= 0.15


def is_toxic(text):
    return any(x in BLOCKLIST for x in words(text))


def exact_key(text):
    return hashlib.sha256(text.lower().encode("utf-8")).hexdigest()


# ---- near-duplicates: MinHash signatures over 3-word shingles ----
def shingles(text, k=3):
    w = words(text)
    return {" ".join(w[i:i + k]) for i in range(len(w) - k + 1)}


def jaccard(a, b):
    return len(a & b) / len(a | b)


PRIME = (1 << 61) - 1
NUM_PERM = 64


def make_hash_params(n, seed=12345):
    params, x = [], seed
    for _ in range(n):                              # tiny LCG: same numbers on every platform
        x = (6364136223846793005 * x + 1442695040888963407) % (1 << 64)
        a = x % PRIME or 1
        x = (6364136223846793005 * x + 1442695040888963407) % (1 << 64)
        params.append((a, x % PRIME))
    return params


HASHES = make_hash_params(NUM_PERM)


def minhash(sh):
    ids = [zlib.crc32(s.encode("utf-8")) for s in sh]
    return [min((a * v + b) % PRIME for v in ids) for a, b in HASHES]


def lsh_candidates(sigs, bands=16):
    rows = NUM_PERM // bands                        # 16 bands x 4 rows
    buckets, pairs = {}, set()
    for doc, sig in sigs.items():
        for band in range(bands):
            key = (band, tuple(sig[band * rows:(band + 1) * rows]))
            for other in buckets.get(key, []):
                pairs.add((other, doc))
            buckets.setdefault(key, []).append(doc)
    return sorted(pairs)


def ngrams(text, n=8):
    w = words(text)
    return {" ".join(w[i:i + n]) for i in range(len(w) - n + 1)}


def main():
    docs = {i: normalise(t) for i, t in enumerate(RAW)}
    print(f"start: {len(docs)} documents")
    dropped = []

    redacted = {i: redact_pii(t) for i, t in docs.items()}
    changed = [i for i in docs if redacted[i] != docs[i]]
    docs = redacted
    for i in changed:
        print(f"PII redacted in doc {i}: ...{docs[i][44:]}")

    def drop(reason_fn, label):
        nonlocal docs
        keep = {}
        for i, t in docs.items():
            reason = reason_fn(t)
            if reason:
                dropped.append((i, label if reason is True else reason))
            else:
                keep[i] = t
        docs = keep
        print(f"after {label}: {len(docs)} documents")

    drop(quality_problem, "quality filters")
    drop(lambda t: not looks_english(t), "language check")
    drop(is_toxic, "toxicity filter")

    seen, keep = {}, {}
    for i, t in docs.items():
        key = exact_key(t)
        if key in seen:
            dropped.append((i, f"exact duplicate of {seen[key]}"))
        else:
            seen[key], keep[i] = i, t
    docs = keep
    print(f"after exact dedup: {len(docs)} documents")

    sh = {i: shingles(t) for i, t in docs.items()}
    sigs = {i: minhash(s) for i, s in sh.items()}
    removed = set()
    for a, b in lsh_candidates(sigs):
        est = sum(x == y for x, y in zip(sigs[a], sigs[b])) / NUM_PERM
        true = jaccard(sh[a], sh[b])
        print(f"  candidate pair ({a}, {b}): MinHash estimate {est:.2f}, true Jaccard {true:.2f}")
        if est >= 0.5 and a not in removed:
            removed.add(b)
            dropped.append((b, f"near duplicate of {a}"))
    docs = {i: t for i, t in docs.items() if i not in removed}
    print(f"after near-dup removal: {len(docs)} documents")

    test_grams = set().union(*(ngrams(normalise(q)) for q in TEST_SET))
    keep = {}
    for i, t in docs.items():
        hits = ngrams(t) & test_grams
        if hits:
            dropped.append((i, f"contaminated: shares {len(hits)} 8-grams with the test set"))
        else:
            keep[i] = t
    docs = keep
    print(f"after decontamination: {len(docs)} documents")

    print("\ndropped:")
    for i, reason in sorted(dropped):
        print(f"  doc {i:2d}: {reason}")
    print("\nkept:")
    for i, t in docs.items():
        print(f"  doc {i:2d}: {t[:70]}{'...' if len(t) > 70 else ''}")


if __name__ == "__main__":
    main()
  1. normalise(text): unicodedata.normalize("NFKC", …) maps look-alike characters (full-width letters, ligatures, non-breaking spaces) to one standard form, then runs of whitespace collapse to one space. Doc 1 differs from doc 0 only in spaces, so after this step they are identical.
  2. EMAIL, PHONE and redact_pii: replace personal data with placeholders such as <EMAIL> instead of deleting the whole record. The text stays useful and the model learns the placeholder, not the address.
  3. quality_problem(text): three heuristics. Fewer than 6 words is a fragment; less than 60% letters is symbol soup; one word making up over 30% of all words is spam. Real pipelines use dozens of such rules, often tuned on samples.
  4. looks_english and is_toxic: toy stand-ins. In production you would use a language identification model and a toxicity classifier, because word lists miss most cases and wrongly flag others.
  5. exact_key: a SHA-256 hash of the lowercased text. Equal hashes mean equal texts, and a set of hashes scales to billions of documents.
  6. shingles, minhash, lsh_candidates: near-duplicate detection, explained in the next section.
  7. ngrams(text, n=8) and the decontamination loop: any document sharing an 8-word sequence with a test question is dropped, so the test set stays a fair exam.
  8. main(): runs the stages in order and records every drop with its reason, the most useful output of a real pipeline when you tune it.
start: 14 documents
PII redacted in doc 3: ...contact me at <EMAIL> or <PHONE> and I will look at the logs.
after quality filters: 11 documents
after language check: 10 documents
after toxicity filter: 9 documents
after exact dedup: 8 documents
  candidate pair (0, 2): MinHash estimate 0.55, true Jaccard 0.60
  candidate pair (10, 13): MinHash estimate 0.56, true Jaccard 0.52
after near-dup removal: 6 documents
after decontamination: 5 documents

dropped:
  doc  1: exact duplicate of 0
  doc  2: near duplicate of 0
  doc  4: too short
  doc  5: mostly symbols
  doc  6: repetitive
  doc  7: language check
  doc  8: toxicity filter
  doc 11: contaminated: shares 8 8-grams with the test set
  doc 13: near duplicate of 10

kept:
  doc  0: How do I reset my password? Go to Settings > Security and click Reset ...
  doc  3: If the export still fails after the update, contact me at <EMAIL> or <...
  doc  9: Invoices can be downloaded as PDF from Billing > History. Each invoice...
  doc 10: To export your data, open Settings > Data and choose Export. Large exp...
  doc 12: Two-factor authentication adds a second step when you log in. You can ...

Only 5 of 14 documents survive, and every drop has a reason. Notice doc 3: its email address and phone number are gone but the useful sentence stays. Notice doc 11: a perfectly good training example, dropped because the same train question is in the test set. If it stayed, the model could memorise the answer and the evaluation would report skill it does not have (lesson 10.8).

How near-duplicates are found: MinHash and LSH

Exact hashing misses near-copies: doc 2 says "How can I reset" and "receive" where doc 0 says "How do I reset" and "get". Web data is full of such variants (templated pages, quoted replies, mirrors), and duplicates make a model over-weight and memorise them. To compare texts by meaning-ish similarity, we first turn each text into a set of shingles, overlapping 3-word sequences, and measure overlap with the Jaccard similarity: the size of the intersection divided by the size of the union.

J(A,B)=|A∩B||A∪B|

In words: the share of distinct shingles the two texts have in common. 1 means the same set, 0 means nothing shared.

Comparing every pair is impossible at scale: a billion documents make about 5 × 1017 pairs. MinHash solves the first half of the problem. Apply a random hash function to every shingle of a document and keep only the minimum value. For two documents, the minima are equal exactly when the shingle with the smallest hash among all their shingles is in both sets, which happens with probability equal to their Jaccard similarity. Repeat with 64 different hash functions and the share of equal positions estimates the Jaccard similarity from a short fixed-size signature: the output shows estimates of 0.55 and 0.56 against true values 0.60 and 0.52.

Locality-sensitive hashing (LSH) solves the second half. Cut each 64-number signature into b=16 bands of r=4 numbers and put the document into one bucket per band. Two documents become candidates if they share a bucket in at least one band, and only candidates are compared. For two documents with similarity s:

P(candidate)=1−(1−sr)b

In words: one band matches with probability s to the power r; the pair is missed only if all b bands fail to match. With r = 4 and b = 16, a pair with s = 0.6 becomes a candidate about 89% of the time, and a pair with s = 0.2 only about 2.5% of the time.

That steep curve is the point: near-duplicates almost always collide, unrelated texts almost never do, and the work grows roughly linearly with the number of documents. Try it below.

Near-duplicate checkerInteractive

Edit the two texts. The checker builds 3-word shingles, computes the exact Jaccard similarity and the chance that LSH with the chosen bands flags the pair.

What changes at pretraining scale

The same stages appear in public descriptions of pretraining datasets (for example the papers behind C4, The Pile, RefinedWeb, FineWeb and Dolma), with three differences. First, scale: pipelines run on clusters over billions of web pages, starting from raw crawls where text must be extracted from HTML and boilerplate (menus, cookie banners) removed. Second, quality classifiers: small models trained to tell "reference-quality" text (for example text resembling Wikipedia or textbooks) from the rest, used to score and keep the best part of the web. Third, mixture weights: how much web, code, books, maths and each language to sample, tuned with small proxy models because it strongly affects the final model Industry practice. Module 5 described these steps from the training side (lesson 5.3). Anthropic has said in general terms that its training data includes public web data, licensed data and data from users who opted in, among other sources; the precise mix and filters are Not public.

For your fine-tuning dataset, the scale is small enough that a person can and should read a random sample of a few hundred records after cleaning. Automated filters are there to make that reading worth doing, not to replace it.

Tuning the filters: precision, recall and who gets filtered out

Every filter makes two kinds of mistakes: it keeps bad records (low precision of cleaning) and drops good ones (low recall). You cannot see either without labelled examples, so build a small audit set: 200 records sampled before filtering, each marked keep or drop by a person, then measure each filter against it.

Heuristics have side effects that are easy to miss. "At least 60% letters" drops code and maths. A blocklist of offensive words drops medical text and discussions about abuse, and it has been shown to remove text written in some dialects more often than others, which can make a model worse for those users. A language check drops code-switched messages. The fix is to apply filters per data type (different thresholds for code), log every drop, and look at what was dropped, not only at what was kept.

For LSH, choosing b and r sets the similarity at which the S-curve rises, roughly (1/b)1/r: about 0.5 for 16 × 4. More hash functions make the estimate and the curve sharper at the cost of memory. After LSH proposes candidates, always confirm with the actual similarity before deleting, as the script does with its estimate threshold.

Finally, deduplicate before you split into train, validation and test. Otherwise two copies of the same record land on both sides of the split and your validation score measures memorisation.

Common mistakes and debugging tips

Splitting first, deduplicating later

A record and its near-copy end up one in training and one in validation. Validation loss looks wonderful and the model fails on genuinely new inputs.

Fix: deduplicate (exact and near) over the whole dataset, then split. For data with groups (several messages from one customer, several files from one repository), split by group.

Trusting regular expressions for PII

The phone pattern in the script misses "four one five, five five five…", names, addresses and account numbers. Regex redaction alone leaves personal data behind.

Fix: combine patterns with a named-entity recogniser or a PII detection tool, keep the raw data in a restricted store, and let reviewers see only redacted text. Better still: do not collect what you do not need.

Filtering so hard that the data loses its variety

After strict filters only polite, medium-length, English questions about two topics remain, and the fine-tuned model breaks on short, messy or unusual inputs, which real users send all the time.

Fix: compare the distribution of lengths, topics and languages before and after cleaning, and keep realistic messy inputs as long as the answers are good.

Not checking for test contamination

Public datasets often contain popular benchmark questions. Training on them inflates scores and hides real weaknesses.

Fix: run an n-gram overlap check against every evaluation set you will use, as the last cleaning step, and repeat it whenever data is added.

Key takeaways

  • Data quality decides most fine-tuning results; record each record's source and permission.
  • Clean in order: normalise, redact PII, cheap filters, exact dedup, near-dedup, decontaminate, then read a sample yourself.
  • MinHash estimates Jaccard similarity from short signatures; LSH banding finds likely near-duplicates without comparing every pair.
  • Every filter drops some good data; measure filters on a small labelled audit set and look at what they remove.

Exercise: add a URL filter and tune LSH

1) Add a quality rule to quality_problem that rejects documents where more than 20% of words are parts of URLs, and add a test document to RAW that it catches. 2) Change lsh_candidates(sigs, bands=16) to 32 bands and then 8 bands. How many candidate pairs does each find, and does the final result change?

Hint

Count URL tokens with re.findall(r"https?://\S+", text) and compare with the number of words. With 32 bands each band has only 2 rows, so dissimilar pairs collide more often.

Show a solution
URL = re.compile(r"https?://\S+|www\.\S+")

def quality_problem(text):
    w = words(text)
    if len(w) < 6:
        return "too short"
    urls = URL.findall(text)
    if len(urls) / (len(text.split()) or 1) > 0.2:
        return "mostly links"
    # ... the existing symbol and repetition checks ...

RAW.append("See https://a.example/1 https://b.example/2 https://c.example/3 for details on everything")

With 32 bands of 2 rows the script still finds the same two candidate pairs (on 8 documents there are few unrelated pairs to collide by chance; on a large corpus you would see many extra candidates for the confirmation step to reject). With 8 bands of 8 rows the pair (10, 13), true Jaccard 0.52, is no longer a candidate, so doc 13 survives and 6 documents remain instead of 5. That is the usual trade-off: LSH settings change cost and recall, and the confirmation check on the estimate protects precision.

Check your understanding

Why does the pipeline normalise text before computing exact-duplicate hashes?

  1. To make hashing faster
  2. Because SHA-256 cannot hash Unicode
  3. So that copies differing only in whitespace or Unicode form get the same hash
A hash changes completely if one byte differs. Normalising first makes trivially different copies byte-identical, so the cheap exact check catches them before the more expensive near-duplicate stage.

What does the fraction of equal positions in two MinHash signatures estimate?

  1. The Jaccard similarity of the two shingle sets
  2. The number of words the texts share
  3. The cosine similarity of their embeddings
Each position's minima match with probability equal to the Jaccard similarity, so the share of matching positions is an unbiased estimate of it. It is a set-overlap measure, unrelated to embeddings.

A training document contains a question that is also in your test set. What should happen to it?

  1. Keep it: more data is always better
  2. Remove it (or remove the test item) so the evaluation stays fair
  3. Keep it but train on it only once
If the model sees a test question during training, the test can no longer tell skill from memorisation. Even one exposure can be enough for a large model to remember an answer.

Lesson 10.3Module 10: Fine-tuning and training

Instruction datasets

  • ⏱ 18 min read
  • Intermediate

Learning objectives

  • Write instruction data in the standard chat format (JSONL with system, user and assistant messages), including multi-turn records.
  • Render records with a chat template and build the loss mask so the model learns only from assistant turns.
  • Know the main ways instruction data is made (human-written, converted tasks, self-instruct, distillation, rejection sampling) and the preference format used by DPO.
  • Validate a dataset automatically: roles, turn order, empty or overlong answers, duplicates, category balance and a stable train/validation split.

Cleaned text is not yet something an assistant can learn from. For supervised fine-tuning (lesson 6.3) the data must be demonstrations: a request and the exact answer you want, written in the conversation format the model uses at inference time. A collection of these is an instruction dataset. This lesson turns the idea into files you can train on.

Analogy: a binder of worked examples for a new hire

When a new support agent joins, a good team lead does not hand over a textbook. They hand over a binder of real tickets, each with the reply a senior colleague would send: short ones and long ones, angry customers, requests that must be politely refused, follow-up questions. The new hire learns the tone, the format and the judgement from the examples. If half the binder's replies are sloppy, the new hire learns sloppiness. An instruction dataset is that binder, and the model is a very literal new hire.

The chat format: one JSON object per line

The common file format is JSONL (JSON Lines): one complete JSON object per line, so files can be streamed, appended and split without parsing everything. Each object holds a messages list with the same roles as the Messages API of module 7: an optional system message, then alternating user and assistant turns, ending with the assistant turn you want the model to learn. Extra fields (here meta) are ignored by training code but invaluable for analysis.

{"messages": [
  {"role": "system", "content": "You are the support assistant for Acme Notes. Be brief, accurate and friendly."},
  {"role": "user", "content": "How do I export all my notes?"},
  {"role": "assistant", "content": "Open Settings > Data and choose Export. Small exports download straight away; large ones are emailed as a zip file."},
  {"role": "user", "content": "What format is the export?"},
  {"role": "assistant", "content": "Each note is a Markdown file, and attachments keep their original format inside the zip."}
], "meta": {"category": "export", "source": "support-team", "license": "internal"}}

(Shown on several lines for reading; in the file it is one line.) The system prompt you train with should be the one you will deploy with. A model fine-tuned under one system prompt and then run under a different one behaves less predictably.

From messages to tokens: the chat template

The model does not see JSON. Each model family defines a chat template that turns the message list into one string with special marker tokens, and the model was post-trained on exactly that layout. You met this in lesson 6.3. A common convention, often called ChatML, looks like this:

<|im_start|>system
You are the support assistant for Acme Notes. Be brief, accurate and friendly.<|im_end|>
<|im_start|>user
How do I reset my password?<|im_end|>
<|im_start|>assistant
Open Settings > Security and choose Reset password. ...<|im_end|>

Other families use different markers. Never write the template by hand for a real model: the tokenizer of an open model ships its template, and tokenizer.apply_chat_template(messages) in the transformers library renders it correctly (used in qlora_train.py, lesson 10.5). A wrong template is one of the most common reasons a fine-tune produces strange output.

The second idea is the loss mask. The training loss is computed only on the tokens of assistant turns (including the end marker, so the model learns to stop). System and user tokens are still read as context, but the model is not trained to produce them. Without the mask, a large part of the learning signal is spent on predicting users' questions, which is not your goal.

How instruction data is made

MethodHow it worksKnown from
Human-writtenpeople write prompts and ideal answers to guidelinespost-training at AI labs; public datasets such as Dolly and OpenAssistant
Converted tasksexisting labelled datasets (translation, QA, classification) rewritten as instructions with templatesFLAN (Wei et al., 2021; Chung et al., 2022)
Self-instructa model generates new instructions and answers from a small seed set; filters remove bad onesSelf-Instruct (Wang et al., 2022)
Distillationa stronger model answers your prompts; you train a smaller model on the answersAlpaca and many open chat models (check the provider's terms)
Rejection samplingsample several answers per prompt from the current model, score them (reward model, unit tests, exact-match checker), keep the best and fine-tune on themcommon in open recipes, as in lesson 6.5 Industry practice

For your own project the most reliable recipe is a mix: a few hundred examples written or carefully edited by people who know the domain, then more generated by a strong model from varied prompts, then filtered and spot-checked by those same people. Rejection sampling is especially powerful when correctness can be checked automatically, such as code with tests or maths with known answers.

Preference data for DPO (lesson 6.5) has a different shape: a prompt with a better and a worse answer.

{"prompt": [{"role": "user", "content": "Why was I charged twice?"}],
 "chosen": [{"role": "assistant", "content": "Usually one charge is a temporary authorisation that disappears within a few days. ..."}],
 "rejected": [{"role": "assistant", "content": "Our system never charges twice. Check your bank."}]}

Libraries differ in the exact field names, so check the trainer you use; the idea (one prompt, a chosen and a rejected answer) is the same everywhere.

What makes a good instruction dataset

  • Correct answers. Every answer is something you would be happy to see in production. The model copies mistakes faithfully.
  • Coverage and variety. All the request types you expect, phrased many ways, short and long, polite and blunt, with typos.
  • The hard cases. Requests to refuse, out-of-scope questions, missing information ("which account?"), and honest "I don't know" answers. If every example has a confident answer, the model learns to always have one.
  • Consistency. One persona, one style, one format. Ten writers with ten styles produce an average of none.
  • Multi-turn examples if your product is a conversation, so the model learns to use earlier turns.
  • Size. Hundreds of excellent examples can shift style and format; thousands to tens of thousands are typical for a narrow task. Quality beats quantity; doubling a noisy dataset rarely helps.

Validating and summarising a dataset

The script builds 14 records for a note-taking app's support assistant, five of them deliberately broken, then validates them, renders one with its loss mask, prints statistics and makes a reproducible train/validation split.

# @run
# instruction_dataset.py: build, validate and summarise a small chat-format instruction dataset.
# Each record is one JSON object per line (JSONL): {"messages": [{"role": ..., "content": ...}, ...], "meta": {...}}
# Prints validation errors, a rendered chat template with its loss mask, token-length stats and a train/val split.
import hashlib
import json
import re
import statistics

SYSTEM = "You are the support assistant for Acme Notes. Be brief, accurate and friendly."


def rec(cat, *turns):
    msgs = [{"role": "system", "content": SYSTEM}]
    for i, text in enumerate(turns):
        msgs.append({"role": "user" if i % 2 == 0 else "assistant", "content": text})
    return {"messages": msgs, "meta": {"category": cat}}


RECORDS = [
    rec("account", "How do I reset my password?",
        "Open Settings > Security and choose Reset password. We email you a link that works for 30 minutes."),
    rec("account", "I never got the reset email.",
        "Check your spam folder first. If it is not there, make sure you typed the address you signed up with, "
        "then request a new link. Each new link cancels the previous one."),
    rec("billing", "Can I get an invoice for last month?",
        "Yes. Go to Billing > History and press Download next to the month you need. Invoices are PDF files."),
    rec("billing", "Why was I charged twice?",
        "Usually one of the two is a temporary card authorisation that disappears within a few days. "
        "If both charges are still there after 5 days, reply with the last 4 digits of the card and we will check."),
    rec("export", "How do I export all my notes?",
        "Open Settings > Data and choose Export. Small exports download straight away; large ones are emailed as a zip file.",
        "What format is the export?",
        "Each note is a Markdown file, and attachments keep their original format inside the zip."),
    rec("sync", "My notes are not syncing between phone and laptop.",
        "First check that both devices show the same account under Settings > Account. Then pull down on the notes list "
        "on the phone to force a sync. If a note still differs, the app keeps both versions and marks one as a conflict."),
    rec("sync", "Does sync work offline?",
        "You can read and edit offline. Changes are queued and sent automatically the next time you are online."),
    rec("refusal", "Give me the email address of the user who owns the note called Q3 plan.",
        "I can't share other users' personal details. If you need access to that note, ask its owner to share it with you."),
    rec("out-of-scope", "Can you write my history essay?",
        "I'm only set up to help with Acme Notes. For the app itself, I can show you how to organise essay drafts in notebooks."),
    # ---- problems the validator must catch ----
    rec("account", "How do I reset my password?",
        "Open Settings > Security and choose Reset password. We email you a link that works for 30 minutes."),  # duplicate
    {"messages": [{"role": "system", "content": SYSTEM}, {"role": "user", "content": "Is there a dark mode?"}],
     "meta": {"category": "ui"}},                                                            # no answer
    {"messages": [{"role": "user", "content": "Hi"}, {"role": "bot", "content": "Hello!"}],
     "meta": {"category": "chitchat"}},                                                      # unknown role
    {"messages": [{"role": "system", "content": SYSTEM}, {"role": "user", "content": "Delete my account"},
                  {"role": "assistant", "content": "   "}], "meta": {"category": "account"}},  # empty answer
    rec("export", "Export to PDF?", " ".join(["Here is a very long rambling answer."] * 120)),  # too long
]

MAX_TOKENS = 512
ROLES = {"system", "user", "assistant"}


def tokens(text):
    # Rough stand-in for a real BPE tokenizer: words, numbers and punctuation marks.
    return re.findall(r"\w+|[^\w\s]", text)


def render(messages):
    # A ChatML-style template (one common convention). Real models each define their own:
    # always use the tokenizer's chat template of the model you fine-tune.
    parts = []
    for m in messages:
        parts.append((f"<|im_start|>{m['role']}\n", False))
        parts.append((m["content"] + "<|im_end|>\n", m["role"] == "assistant"))   # True = train on it
    return parts


def validate(r):
    msgs = r.get("messages")
    if not isinstance(msgs, list) or not msgs:
        return "no messages list"
    for m in msgs:
        if m.get("role") not in ROLES:
            return f"unknown role '{m.get('role')}'"
        if not isinstance(m.get("content"), str) or not m["content"].strip():
            return f"empty {m.get('role')} message"
    order = [m["role"] for m in msgs if m["role"] != "system"]
    if any(m["role"] == "system" for m in msgs[1:]):
        return "system message not first"
    if order[0] != "user" or any(a == b for a, b in zip(order, order[1:])):
        return "turns must alternate user/assistant, starting with user"
    if order[-1] != "assistant":
        return "last turn is not an assistant answer"
    n = sum(len(tokens(text)) for text, _ in render(msgs))
    if n > MAX_TOKENS:
        return f"too long ({n} tokens > {MAX_TOKENS})"
    return None


def fingerprint(r):
    return hashlib.sha256(json.dumps(r["messages"], sort_keys=True).encode("utf-8")).hexdigest()


def main():
    good, seen = [], set()
    print(f"records in: {len(RECORDS)}")
    for i, r in enumerate(RECORDS):
        problem = validate(r)
        if problem is None and fingerprint(r) in seen:
            problem = "exact duplicate"
        if problem:
            print(f"  record {i:2d} rejected: {problem}")
            continue
        seen.add(fingerprint(r))
        good.append(r)
    print(f"valid records: {len(good)}")

    print("\nrendered record 0 (lines marked + are trained on, - are masked out):")
    for text, train in render(good[0]["messages"]):
        for line in text.rstrip("\n").split("\n"):
            print(f"  {'+' if train else '-'} {line}")

    lengths, trained = [], []
    for r in good:
        parts = render(r["messages"])
        lengths.append(sum(len(tokens(t)) for t, _ in parts))
        trained.append(sum(len(tokens(t)) for t, keep in parts if keep))
    lengths.sort()
    p95 = lengths[min(len(lengths) - 1, round(0.95 * (len(lengths) - 1)))]
    print(f"\ntokens per record: min {lengths[0]}, median {statistics.median(lengths):.0f}, "
          f"p95 {p95}, max {lengths[-1]}")
    print(f"share of tokens that carry loss: {sum(trained) / sum(lengths):.0%}")
    cats = {}
    for r in good:
        cats[r["meta"]["category"]] = cats.get(r["meta"]["category"], 0) + 1
    print("categories:", ", ".join(f"{k} {v}" for k, v in sorted(cats.items())))

    # Deterministic split: order by a hash of the content, so a record never moves between runs.
    ordered = sorted(good, key=fingerprint)
    n_val = max(1, round(0.2 * len(ordered)))
    val, train = ordered[:n_val], ordered[n_val:]
    print(f"\nsplit: {len(train)} train, {len(val)} validation")
    print("validation questions:", " | ".join(r["messages"][1]["content"] for r in val))
    line = json.dumps(train[0], ensure_ascii=False)
    print(f"\nfirst JSONL line of train.jsonl ({len(line)} characters):")
    print(line[:150] + " ...")


if __name__ == "__main__":
    main()
  1. rec(cat, *turns): a helper that builds a record with the system prompt and alternating user/assistant turns, plus a meta.category for statistics.
  2. The last five entries of RECORDS are broken on purpose: a duplicate, a record ending with a user turn, the role "bot", an empty answer, and a 1,000-token answer.
  3. tokens(text): a rough word-and-punctuation splitter standing in for the real tokenizer; real counts must come from the model's tokenizer, since limits are in its tokens.
  4. render(messages): produces ChatML-style pieces, each with a flag saying whether it carries loss (only assistant content and its end marker).
  5. validate(r): checks known roles, non-empty content, the system message first, strict user/assistant alternation starting with the user, an assistant turn at the end, and a token limit. It returns the first problem as a readable message.
  6. fingerprint(r): a hash of the messages, used to reject exact duplicates and to order records for the split.
  7. The statistics block prints token lengths (minimum, median, 95th percentile, maximum), the share of tokens that carry loss, and counts per category.
  8. sorted(good, key=fingerprint): a split by content hash puts each record in the same split on every run, even after you add new records, so validation never silently leaks into training.
records in: 14
  record  9 rejected: exact duplicate
  record 10 rejected: last turn is not an assistant answer
  record 11 rejected: unknown role 'bot'
  record 12 rejected: empty assistant message
  record 13 rejected: too long (1013 tokens > 512)
valid records: 9

rendered record 0 (lines marked + are trained on, - are masked out):
  - <|im_start|>system
  - You are the support assistant for Acme Notes. Be brief, accurate and friendly.<|im_end|>
  - <|im_start|>user
  - How do I reset my password?<|im_end|>
  - <|im_start|>assistant
  + Open Settings > Security and choose Reset password. We email you a link that works for 30 minutes.<|im_end|>

tokens per record: min 74, median 93, p95 125, max 125
share of tokens that carry loss: 40%
categories: account 2, billing 2, export 1, out-of-scope 1, refusal 1, sync 2

split: 7 train, 2 validation
validation questions: Can you write my history essay? | Give me the email address of the user who owns the note called Q3 plan.

first JSONL line of train.jsonl (559 characters):
{"messages": [{"role": "system", "content": "You are the support assistant for Acme Notes. Be brief, accurate and friendly."}, {"role": "user", "conte ...

Five records were rejected, each with a precise reason. The rendered record shows the loss mask: only the assistant's line is marked +. Across the dataset, 40% of tokens carry loss; the rest is system prompt and questions. The category counts reveal a gap: one example each for export, refusal and out-of-scope is far too few for a real project, and the validation set happens to contain exactly the refusal and out-of-scope examples, so the training set has none of either. That is the kind of problem statistics catch and a quick glance does not: with real data, stratify the split by category.

JSONL record checkerInteractive

Paste JSONL (one record per line) or load an example. The same rules as validate() run in your browser; valid records are shown with their loss mask.

    Packing, truncation and template traps

    Packing. Records have very different lengths, and padding short ones to the longest wastes GPU time. Packing concatenates several records into one sequence up to the maximum length. To stop one example from attending to another, good implementations reset attention at record boundaries (block-diagonal masks or position resets); naive packing lets tokens see unrelated earlier records, which usually hurts little but is not free.

    Truncation. If a record is longer than the maximum sequence length, cutting the end removes the assistant answer, the only part with loss, and can leave a record that teaches nothing or teaches the model to stop mid-sentence. Filter or split overlong records instead, as the validator's token limit does.

    Template traps. Some templates add a beginning-of-sequence token themselves; tokenising the rendered string with special tokens on adds a second one. Some templates insert a default system prompt when none is given. Some strip "thinking" sections from earlier assistant turns. After rendering, decode a few training examples back to text and read them, and compare with what apply_chat_template(..., add_generation_prompt=True) produces at inference time: training and inference must agree token for token up to the answer.

    Mixing. A narrow dataset makes the model narrow. Many recipes mix 10–30% general instruction data into a domain dataset to keep general helpfulness, the "replay" idea measured in lesson 10.4 Industry practice.

    Common mistakes and debugging tips

    The model never stops talking

    Training examples lacked the end-of-turn token, or it was masked out, so the model never learned to produce it and keeps generating new "user" turns.

    Fix: include the end marker in the trained (unmasked) part of every assistant turn, as render() does, and check one decoded example.

    Training on the prompts

    Without a loss mask the model spends most of its learning on predicting questions; with long system prompts it may even start repeating them in answers.

    Fix: mask everything except assistant turns (labels of -100 in PyTorch code), and print the share of tokens that carry loss as a sanity check.

    A dataset with no refusals or "I don't know"

    Every example has a confident, helpful answer, so the fine-tuned model answers everything confidently, including questions outside its knowledge.

    Fix: add examples where the right answer is to ask a clarifying question, decline, or say what the assistant cannot know, written in the same style as the rest.

    Generated data that all sounds the same

    Thousands of synthetic examples start with "Certainly! Here's…" and use the same structure. The model learns those tics and little else.

    Fix: vary the generation prompts (persona, length, difficulty), deduplicate by n-grams across answers, and measure how often common openings appear.

    Key takeaways

    • Instruction data is JSONL: a messages list per line with system, user and assistant roles, ending in the assistant answer to learn.
    • Render with the model's own chat template and compute loss only on assistant tokens, including the end marker.
    • Data comes from people, converted tasks, self-instruct, distillation and rejection sampling; preference data pairs a chosen and a rejected answer.
    • Validate automatically, look at statistics, and split by content hash (and by category) so the split is stable and fair.

    Exercise: write the files and fix the split

    1) Extend instruction_dataset.py to write train.jsonl and val.jsonl (one json.dumps per line, UTF-8). These are the files qlora_train.py reads. 2) Make the split stratified: take about 20% of each category for validation, so every category appears on both sides when it has at least two records.

    Hint

    Group the valid records by meta.category, sort each group by fingerprint, and send the first round(0.2 × len(group)) to validation (at least one when the group has two or more). Open files with encoding="utf-8" and use ensure_ascii=False so accented text stays readable.

    Show a solution
    groups = {}
    for r in good:
        groups.setdefault(r["meta"]["category"], []).append(r)
    train, val = [], []
    for cat, rs in sorted(groups.items()):
        rs.sort(key=fingerprint)
        k = max(1, round(0.2 * len(rs))) if len(rs) >= 2 else 0
        val += rs[:k]
        train += rs[k:]
    for name, rows in (("train.jsonl", train), ("val.jsonl", val)):
        with open(name, "w", encoding="utf-8") as f:
            for r in rows:
                f.write(json.dumps(r, ensure_ascii=False) + "\n")
    print(f"wrote {len(train)} train and {len(val)} validation records")

    With the nine valid records, the account, billing and sync categories each send one record to validation; the single-record categories stay in training. With a real dataset you would have enough examples per category to give each one a meaningful validation share.

    Check your understanding

    Which tokens normally carry loss during supervised fine-tuning of a chat model?

    1. Every token in the conversation
    2. The assistant's answer tokens, including the end-of-turn marker
    3. Only the system prompt
    The goal is to learn to produce answers, so loss is computed on assistant tokens. The end marker is included so the model learns when to stop. System and user tokens are context, not targets.

    You fine-tune with a hand-written template, but at inference you use the tokenizer's official chat template. What is the likely result?

    1. No difference: templates are just formatting
    2. Faster inference
    3. Odd or degraded output, because the model sees a layout it was not trained on
    Marker tokens and their exact placement are part of what the model learned. Training on one layout and serving another creates a mismatch the model never practised.

    Why does instruction_dataset.py order records by a hash of their content before splitting?

    1. So each record stays in the same split on every run, even when records are added
    2. Because hashing makes training faster
    3. To put the longest records into validation
    A content-hash order is deterministic and independent of insertion order, so the split is reproducible and a record never moves from validation to training, which would leak information.

    Lesson 10.4Module 10: Fine-tuning and training

    Fine-tuning concepts

    • ⏱ 16 min read
    • Advanced

    Learning objectives

    • Distinguish full fine-tuning from parameter-efficient fine-tuning, and supervised fine-tuning from preference tuning.
    • Choose sensible values for the main hyperparameters: learning rate, schedule and warm-up, epochs, batch size and gradient accumulation, sequence length.
    • Recognise overfitting and catastrophic forgetting in loss curves, and use early stopping and replay data against them.
    • Read a minimal PyTorch fine-tuning step and know what each line does.

    You now have a clean, validated dataset. Before choosing a method (LoRA, in the next lesson), it helps to understand the decisions every fine-tuning run involves, whatever the method: how big the steps are, how long to train, how to tell when it is going wrong. This lesson measures each of them on the bigram model of lesson 10.1, where a run takes milliseconds, so you can see the effects clearly.

    Analogy: retuning a well-tuned guitar

    A guitar that is already in tune for one song needs only small turns of the pegs to suit another. Turn too hard and you overshoot; keep turning and you may snap a string or detune the others. Turn too little and nothing changes. Fine-tuning is the same: the weights are already good, so the learning rate must be small, the number of turns limited, and you keep checking that the other strings (the model's general abilities) still sound right.

    Kinds of fine-tuning

    ChoiceOptionWhat it means
    Which weights changeFull fine-tuningevery weight is trainable; the most expressive, the most memory (about 16 bytes per parameter with Adam, lesson 10.6) and the most forgetting
    Parameter-efficient (PEFT)the original weights are frozen and a small number of new parameters are trained: LoRA adapters (most common), prefix or prompt tuning, adapter layers
    What signal is usedSFTimitate demonstration answers with the masked cross-entropy loss (lesson 10.3)
    Preference tuningprefer chosen over rejected answers, for example with DPO (lesson 6.5); usually after SFT
    RL with a rewardgenerate, score with a reward model or a checker (tests, exact answers), update; the most powerful and the hardest to run well

    For a first project the default is SFT with LoRA on an instruct model. Everything below applies to it.

    The loss you optimise

    SFT uses the same next-token cross-entropy as pretraining, with one change from lesson 10.3: only the assistant tokens count. If A is the set of positions inside assistant turns, the loss for one conversation is the average negative log-probability the model gives to the correct token at those positions:

    L=−1|A|∑t∈Alogpθ(xt∣x<t)

    In words: for every token of the assistant's answer, look at the probability the model assigned to it given everything before it (system prompt, question, earlier answer tokens), take the log, average, and flip the sign. Lower is better; it is the quantity the training loop pushes down.

    In PyTorch code the mask is written by setting the label of every non-assistant token to -100, the value that the cross-entropy function ignores by default. You will see exactly that in qlora_train.py (lesson 10.5).

    The hyperparameters that matter

    • Learning rate. The most important one. Fine-tuning uses much smaller rates than pretraining from scratch would, because you want to adjust, not overwrite. Typical starting points in public recipes: around 1e-5 to 2e-5 for full fine-tuning and around 1e-4 to 2e-4 for LoRA, which trains fewer, freshly initialised parameters Industry practice. Always confirm with a small sweep.
    • Schedule and warm-up. Start at a small rate, ramp up over the first few percent of steps (warm-up, so the optimiser's statistics settle before large steps), then decay, often with a cosine curve, to near zero.
    • Epochs. One epoch is one pass through the data. Small datasets typically use 1 to 3 epochs; more usually means memorising. Watch validation loss rather than trusting a fixed number.
    • Batch size and gradient accumulation. The effective batch is the number of sequences per optimiser step. When only 2 fit in memory, run 8 forward/backward passes and step once: an effective batch of 16 (lesson 10.6 explains the memory side).
    • Maximum sequence length. Set it from your data's length statistics (the 95th percentile from lesson 10.3, with margin), not from the model's maximum. Memory for activations grows with it.
    • Precision. Train in bf16 mixed precision on GPUs that support it: half the memory of fp32 with the same range, so no loss scaling is needed.

    Measuring learning rate, training length and forgetting

    The script reuses the bigram model and texts of lesson 10.1 and runs three experiments: four learning rates; one long run with validation every 50 steps; and fine-tuning with different shares of general text mixed into the code data.

    # @run
    # finetune_concepts.py: the knobs of fine-tuning, measured on the tiny bigram model of pretrain_vs_finetune.py.
    # 1) learning rate, 2) how long to train (overfitting + early stopping), 3) catastrophic forgetting and
    # how mixing in some general "replay" data reduces it. Same texts and model as lesson 10.1, self-contained.
    import numpy as np
    
    GENERAL = (
        "The river was quiet in the early morning, and the town had not woken up yet. A baker opened his shop and "
        "the smell of fresh bread moved slowly along the street. Children would soon walk to school, and their "
        "parents would hurry to the station to catch the first train. Most people in the town knew each other by "
        "name. They talked about the weather, the price of vegetables and the new bridge that the council had "
        "promised for many years. In the evening the square filled with music. Old friends sat at small tables, "
        "drank tea and told the same stories they had told the week before, and nobody minded at all. When the "
        "rain came in autumn, the river rose and the fishermen pulled their boats higher onto the stones. A "
        "teacher wrote a short history of the town and read it aloud in the library, and the room was full. "
        "She explained how the first families had arrived, how they built the mill, and why the market was held "
        "on the same day every week. After the reading, people asked questions and shared memories of their "
        "grandparents. It was late when the last of them walked home under the lamps."
    )
    GENERAL_VAL = (
        "On Sunday the market was busy. A farmer sold apples and honey, and a young woman played the violin "
        "near the fountain while people listened and smiled. Later the sky turned grey and everyone went home."
    )
    DOMAIN = (
        "def mean(values):\n    total = 0\n    for v in values:\n        total += v\n    return total / len(values)\n\n"
        "def clamp(x, low, high):\n    if x < low:\n        return low\n    if x > high:\n        return high\n    return x\n\n"
        "for i in range(10):\n    print(i, mean([i, i + 1]))\n"
    )
    DOMAIN_VAL = (
        "def count_words(text):\n    words = text.split()\n    return len(words)\n\n"
        "def first(items, default=None):\n    for item in items:\n        return item\n    return default\n"
    )
    
    chars = sorted(set(GENERAL + GENERAL_VAL + DOMAIN + DOMAIN_VAL))
    idx = {c: i for i, c in enumerate(chars)}
    V = len(chars)
    
    
    def counts(text):
        C = np.zeros((V, V))
        for a, b in zip(text, text[1:]):
            C[idx[a], idx[b]] += 1
        return C
    
    
    def loss(W, C):
        m = W.max(1, keepdims=True)
        logp = W - m - np.log(np.exp(W - m).sum(1, keepdims=True))
        return float(-(C * logp).sum() / C.sum())
    
    
    def train(W, C, steps, lr, every=None, evals=()):
        """Gradient descent; if `every` is set, also return the losses on `evals` every `every` steps."""
        W, n, history = W.copy(), C.sum(), []
        for step in range(steps + 1):
            if every and step % every == 0:
                history.append((step, [loss(W, E) for E in evals]))
            if step == steps:
                break
            P = np.exp(W - W.max(1, keepdims=True))
            P /= P.sum(1, keepdims=True)
            W -= lr * (C.sum(1, keepdims=True) * P - C) / n
        return W, history
    
    
    C_gen, C_gen_val = counts(GENERAL), counts(GENERAL_VAL)
    C_dom, C_dom_val = counts(DOMAIN), counts(DOMAIN_VAL)
    rng = np.random.default_rng(0)
    W_pre, _ = train(rng.normal(0, 0.01, size=(V, V)), C_gen, 3000, 20.0)   # the "pretrained" model
    print(f"pretrained model: general val {loss(W_pre, C_gen_val):.3f}, code val {loss(W_pre, C_dom_val):.3f}\n")
    
    print("1) learning rate (150 fine-tuning steps each)")
    print(f"   {'lr':>6}{'code val':>10}{'general val':>13}")
    for lr in (0.5, 5.0, 20.0, 200.0):
        W, _ = train(W_pre, C_dom, 150, lr)
        print(f"   {lr:>6}{loss(W, C_dom_val):>10.3f}{loss(W, C_gen_val):>13.3f}")
    
    print("\n2) how long to fine-tune (lr 20): code train / code val / general val")
    _, hist = train(W_pre, C_dom, 1600, 20.0, every=50, evals=(C_dom, C_dom_val, C_gen_val))
    shown = {0, 50, 100, 200, 400, 800, 1600}
    best_step, best_val = min(((s, l[1]) for s, l in hist), key=lambda t: t[1])
    for step, (tr, va, ge) in hist:
        if step in shown or step == best_step:
            mark = "  <- best code val (early stopping picks this)" if step == best_step else ""
            print(f"   step {step:>5}: {tr:.3f} / {va:.3f} / {ge:.3f}{mark}")
    
    print("\n3) forgetting vs replay: mix general text into the fine-tuning data (lr 20, 150 steps)")
    print(f"   {'general share':>13}{'code val':>10}{'general val':>13}")
    for share in (0.0, 0.1, 0.3, 0.5):
        # Weight the general counts so they make up `share` of all training pairs.
        g = 0.0 if share == 0 else share / (1 - share) * C_dom.sum() / C_gen.sum()
        W, _ = train(W_pre, C_dom + g * C_gen, 150, 20.0)
        print(f"   {share:>13.0%}{loss(W, C_dom_val):>10.3f}{loss(W, C_gen_val):>13.3f}")
    1. The texts, counts and loss are those of lesson 10.1, copied so the file runs on its own.
    2. train(W, C, steps, lr, every=None, evals=()): the same gradient descent, but it can also record the loss on several evaluation sets every every steps. That record is a learning curve.
    3. W_pre: the pretrained starting point, identical to lesson 10.1.
    4. Experiment 1 fine-tunes for 150 steps at learning rates 0.5, 5, 20 and 200 and prints code and English validation loss.
    5. Experiment 2 fine-tunes for 1,600 steps, records train loss, code validation loss and English validation loss, and marks the step with the lowest code validation loss: the point early stopping would choose.
    6. Experiment 3: C_dom + g * C_gen adds general-text counts scaled so they make up a chosen share of all training pairs. This is replay: reminding the model of old data while it learns new data.
    pretrained model: general val 2.584, code val 4.730
    
    1) learning rate (150 fine-tuning steps each)
           lr  code val  general val
          0.5     3.383        2.782
          5.0     3.130        3.604
         20.0     3.578        4.693
        200.0     6.353        7.945
    
    2) how long to fine-tune (lr 20): code train / code val / general val
       step     0: 5.129 / 4.730 / 2.584
       step    50: 1.611 / 3.187 / 3.805  <- best code val (early stopping picks this)
       step   100: 1.400 / 3.386 / 4.327
       step   200: 1.350 / 3.718 / 4.938
       step   400: 1.335 / 4.032 / 5.480
       step   800: 1.329 / 4.325 / 5.983
       step  1600: 1.326 / 4.610 / 6.468
    
    3) forgetting vs replay: mix general text into the fine-tuning data (lr 20, 150 steps)
       general share  code val  general val
                  0%     3.578        4.693
                 10%     3.293        3.697
                 30%     3.111        3.113
                 50%     3.081        2.846
    1357 08001,600 fine-tuning steps loss (nats) best code val (step 50) code train code val general (English) val
    Output of experiment 2, drawn every 50 steps. Training loss keeps improving while validation loss turns upward after step 50: from there on the model memorises the 266 training characters. English loss rises the whole time: forgetting.

    What the numbers say:

    • Learning rate. 0.5 barely moves the model (little gain, little forgetting); 5 gives the best code score here; 20 overshoots into overfitting within 150 steps; 200 destroys both skills, with losses far worse than a uniform guess. There is a sweet spot, and it must be found by measurement.
    • Overfitting. Training loss falls from 5.13 to 1.33, while code validation loss is best at step 50 (3.187) and then rises steadily. Without a validation set you would happily train for 1,600 steps and get a worse model. Early stopping means evaluating regularly and keeping the best checkpoint.
    • Forgetting. English loss rises at every step, from 2.58 to 6.47. Fine-tuning only on new data pulls every shared weight toward the new task.
    • Replay. Mixing in 30% general text keeps English at 3.11 instead of 4.69 after 150 steps. In this toy it even improves code validation, because the extra data also acts as a regulariser against memorising 266 characters. With real models, replay usually costs a little on the target task in exchange for keeping general abilities; how much is something to measure (lesson 10.8).

    Simplified implementation Simplified

    In the bigram model every parameter is shared between English and code, so forgetting is extreme. Large models have far more capacity and forget less per step, and LoRA restricts how much can change (lesson 10.5). The direction of each effect is the same; the sizes are exaggerated here.

    The same loop in PyTorch

    Modules 2 to 5 built everything in NumPy so nothing was hidden. Real fine-tuning uses PyTorch, whose automatic differentiation computes the gradients you wrote by hand. One fine-tuning step with gradient accumulation looks like this (the full runnable version is qlora_train.py in the next lesson; PyTorch is not installed or run by this course's tests):

    model.train()
    for step, (input_ids, attention_mask, labels) in enumerate(loader):
        out = model(input_ids=input_ids, attention_mask=attention_mask, labels=labels)
        loss = out.loss / accum_steps          # labels == -100 are ignored: the loss mask
        loss.backward()                        # autograd fills .grad of trainable weights
        if (step + 1) % accum_steps == 0:
            torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)   # tame rare huge gradients
            optimizer.step()                   # AdamW update
            scheduler.step()                   # warm-up then cosine decay
            optimizer.zero_grad()
    1. model(..., labels=labels): Hugging Face causal language models shift the labels by one position internally and return the masked cross-entropy as out.loss.
    2. loss / accum_steps: gradients add up across the accumulated mini-batches, so each is scaled to give the average.
    3. clip_grad_norm_: if the total gradient length exceeds 1.0 it is scaled down, which prevents a single odd batch from wrecking the weights.
    4. optimizer.step() then scheduler.step() then zero_grad(): update, adjust the learning rate, clear gradients for the next accumulation round.
    Why small steps preserve knowledge, and other ways to fight forgetting

    A pretrained model sits in a region of weight space where many abilities are good at once. Fine-tuning moves it toward a point that is good for your data. Small learning rates and few steps keep it close to where it started, so abilities that your data does not exercise are mostly untouched. This is the same intuition as the KL penalty in RLHF (lesson 6.4), which explicitly punishes the policy for drifting away from the reference model.

    Methods against forgetting, roughly from simplest to most involved: lower learning rate and early stopping; replay or mixing general data; parameter-efficient methods such as LoRA, which limit the size and rank of the change (Biderman et al., 2024, "LoRA Learns Less and Forgets Less", measured this trade-off); explicit regularisers that keep weights near their original values (L2-SP, or elastic weight consolidation, which weights each parameter by how important it was for the old task); and model merging, which averages a fine-tuned model with the original to recover lost abilities.

    Effective batch size and learning rate interact: larger batches give less noisy gradients and usually tolerate larger rates. If you change one, re-check the other. And seeds matter more than people expect on small datasets: two runs with different seeds can differ by several points on an evaluation. Run at least two seeds before trusting a small improvement (lesson 10.8 shows how to put an interval around a score).

    Common mistakes and debugging tips

    Loss goes to NaN or jumps up early

    The learning rate is too high, warm-up is missing, or fp16 overflowed. The run at lr 200 in the script is the toy version of this.

    Fix: lower the rate by 3 to 10 times, add warm-up, clip gradients, and use bf16 instead of fp16 if the GPU supports it.

    Judging by training loss

    Training loss near zero feels like success; it usually means memorisation, as experiment 2 shows.

    Fix: evaluate on a held-out validation set at regular intervals, keep the best checkpoint, and also check a few general prompts for forgetting.

    Too many epochs on a small dataset

    Ten epochs on 500 examples produces a model that repeats training answers word for word, even for slightly different questions.

    Fix: start with 1 to 3 epochs, watch validation loss each epoch, and add data rather than epochs.

    Changing several things at once

    New data, new rate and new rank in one run; the result is better or worse and nobody knows why.

    Fix: change one thing per run, log every setting with the result, and keep a fixed evaluation set.

    Key takeaways

    • SFT minimises the masked next-token cross-entropy; full fine-tuning trains every weight, PEFT trains a small add-on.
    • The learning rate has a sweet spot; small steps adjust, large steps overwrite or diverge.
    • Training loss always falls; validation loss tells you when to stop.
    • Fine-tuning causes forgetting; low rates, early stopping, replay data and LoRA reduce it.

    Exercise: early stopping with patience

    Add a fourth experiment to finetune_concepts.py: train with lr 5 for up to 2,000 steps, evaluate code validation loss every 25 steps, and stop when it has not improved for 4 evaluations in a row (patience 4). Print the step it stopped at, the best step, and both validation losses at the best step.

    Hint

    Write a loop that calls train(W, C_dom, 25, 5.0) repeatedly on the current weights, keeps a copy of the best weights, and counts evaluations without improvement.

    Show a solution
    W, best, best_W, best_step, waited = W_pre, float("inf"), W_pre, 0, 0
    for step in range(25, 2001, 25):
        W, _ = train(W, C_dom, 25, 5.0)
        v = loss(W, C_dom_val)
        if v < best - 1e-4:
            best, best_W, best_step, waited = v, W, step, 0
        else:
            waited += 1
            if waited == 4:
                break
    print(f"stopped at {step}, best step {best_step}: code val {best:.3f}, "
          f"general val {loss(best_W, C_gen_val):.3f}")

    It prints stopped at 200, best step 100: code val 3.102, general val 3.375. With lr 5 the best point comes later than with lr 20 (smaller steps need more of them), and the best code score is a little better than any run in experiment 1, with less forgetting. The patience value trades extra compute for robustness to noisy evaluations.

    Check your understanding

    Training loss keeps falling but validation loss has risen for the last three evaluations. What is happening?

    1. The learning rate is too small
    2. The model is underfitting
    3. The model is overfitting; stop and keep the best earlier checkpoint
    Falling training loss with rising validation loss is the classic sign of memorising the training set. Early stopping keeps the checkpoint with the best validation score.

    In experiment 3, why did mixing in general text reduce the rise of the English loss?

    1. The general examples keep pulling the shared weights back toward what was learned in pretraining
    2. It lowered the learning rate
    3. It removed the code from the training data
    Replay keeps the old task in the objective, so the optimiser cannot improve on code by sacrificing English for free. The learning rate and the code data were unchanged.

    Only 2 sequences fit in GPU memory, but you want an effective batch of 16. What do you do?

    1. Use a learning rate 8 times larger
    2. Accumulate gradients over 8 forward/backward passes before each optimiser step
    3. Train for 8 times more epochs
    Gradient accumulation sums gradients of several small batches (each scaled by 1/8) and updates once, which is mathematically the same as one batch of 16 for most models, at the memory cost of a batch of 2.

    Lesson 10.5Module 10: Fine-tuning and training

    LoRA and QLoRA

    • ⏱ 23 min read
    • Advanced

    Learning objectives

    • Explain the LoRA idea (a frozen weight plus a trainable low-rank update BA) and why it needs so few parameters.
    • Implement LoRA from scratch in NumPy, including its initialisation, scaling and merging.
    • Explain what QLoRA adds: a 4-bit NF4 frozen base model, double quantisation and paged optimisers.
    • Read a real QLoRA training script for an open-weight model and know which settings to choose.

    Full fine-tuning of an 8-billion-parameter model needs well over 100 GB of GPU memory (lesson 10.6). Yet people fine-tune such models on a single 24 GB gaming GPU every day. Two ideas make that possible: LoRA trains a tiny add-on instead of the model, and QLoRA stores the frozen model in 4 bits. Together they are how a small team can adapt an open-weight model on one GPU.

    Analogy: sticky notes on a printed textbook

    To adapt a 1,000-page textbook for your class you could reprint every page with your changes: expensive, and you now own a second heavy book. Or you could leave the book as it is and add a thin stack of sticky notes that adjust specific passages. The notes are cheap, you can keep several sets for different classes, and peeling them off gives you the original back. LoRA adapters are those notes. QLoRA additionally shrinks the textbook to a pocket edition, small print but still readable, so it fits in your bag while you write the notes.

    The LoRA idea

    A transformer is mostly linear layers: the query, key, value and output projections of attention and the matrices of the feed-forward network (module 4). Each has a weight matrix W0 of shape dout×din, for example 4,096 × 4,096 = 16.8 million numbers. Fine-tuning changes it to W0+ΔW. The observation behind LoRA (Hu et al., 2021, "LoRA: Low-Rank Adaptation of Large Language Models") is that the useful change ΔW has low rank: it can be written, approximately, as the product of a tall thin matrix and a short wide one.

    h=W0x+αrBAx,B∈ℝdout×r,A∈ℝr×din

    In words: the output is the frozen layer's output plus a correction. The correction first squeezes the input down to r numbers with A, then expands them back with B, and is scaled by alpha over r. Only A and B are trained.

    The parameter count is the whole point. A full update of a 4,096 × 4,096 layer has 16.8 million numbers; with rank r=16, A and B together have 16×(4096+4096)=131,072, under 1%. Three details make it work in practice:

    • Initialisation. A starts random and B starts at zero, so BA=0 and the adapted model is exactly the original at step 0. Training starts from the pretrained behaviour, not from noise.
    • Scaling by α/r: changing the rank then does not require retuning the learning rate as much. A common choice is α=2r or α=r Industry practice.
    • Merging. After training, W0+αrBA can be computed once and stored as an ordinary weight, so inference costs nothing extra. Or keep the adapter separate (megabytes to a few hundred megabytes: about 84 MB for rank 16 on all layers of an 8B model) and swap adapters for different tasks on one base model.
    x W0 (frozen) 🔒 d_out × d_in, e.g. 4096 × 4096 A r numbers B + h × α / r (trained)
    LoRA adds a narrow trainable path next to each frozen weight. The bottleneck of r numbers (often 8 to 64) is what keeps the update small and low-rank.

    LoRA from scratch in NumPy

    The script builds one 64 × 64 "pretrained" layer and a new task whose true change has rank 2. With only 48 noisy training examples, it compares full fine-tuning of all 4,096 entries with LoRA at ranks 1, 2, 4 and 8, all with the same Adam optimiser, then merges an adapter and checks the outputs are unchanged.

    # @run
    # lora_numpy.py: LoRA from scratch on one linear layer, in NumPy.
    # A frozen "pretrained" weight W0 must be adapted to a new task whose true change is low-rank.
    # We compare full fine-tuning (train every entry of a delta matrix) with LoRA adapters of
    # rank 1, 2, 4 and 8, then merge the adapter into the weight and check nothing changed.
    import numpy as np
    
    rng = np.random.default_rng(0)
    d_in, d_out = 64, 64
    n_train, n_val = 48, 1000          # few examples, like a small fine-tuning set
    
    W0 = rng.normal(0, 1 / np.sqrt(d_in), size=(d_out, d_in))        # "pretrained", frozen
    U = rng.normal(size=(d_out, 2))
    V = rng.normal(size=(2, d_in))
    delta_true = 0.15 * (U @ V) / np.sqrt(d_in)                       # the new task: a rank-2 change
    W_task = W0 + delta_true
    
    
    def make_data(n):
        X = rng.normal(size=(n, d_in))
        Y = X @ W_task.T + 0.1 * rng.normal(size=(n, d_out))          # noisy labels
        return X, Y
    
    
    Xtr, Ytr = make_data(n_train)
    Xva, Yva = make_data(n_val)
    
    
    def mse(W, X, Y):
        return float(np.mean((X @ W.T - Y) ** 2))
    
    
    class Adam:
        def __init__(self, params, lr):
            self.p, self.lr, self.t = params, lr, 0
            self.m = [np.zeros_like(p) for p in params]
            self.v = [np.zeros_like(p) for p in params]
    
        def step(self, grads):
            self.t += 1
            for p, g, m, v in zip(self.p, grads, self.m, self.v):
                m[:] = 0.9 * m + 0.1 * g
                v[:] = 0.999 * v + 0.001 * g * g
                mh, vh = m / (1 - 0.9 ** self.t), v / (1 - 0.999 ** self.t)
                p -= self.lr * mh / (np.sqrt(vh) + 1e-8)               # in-place update
    
    
    def train_full(steps=400, lr=0.01):
        D = np.zeros((d_out, d_in))                                   # trainable: every entry
        opt = Adam([D], lr)
        for _ in range(steps):
            err = Xtr @ (W0 + D).T - Ytr                              # (n, d_out)
            grad = 2 * err.T @ Xtr / err.size                         # dLoss/dW
            opt.step([grad])
        return W0 + D, D.size
    
    
    def train_lora(r, alpha=16, steps=400, lr=0.01):
        s = alpha / r                                                 # LoRA scaling
        A = rng.normal(0, 1 / np.sqrt(d_in), size=(r, d_in))          # random init
        B = np.zeros((d_out, r))                                      # zero init: starts as W0
        opt = Adam([A, B], lr)
        for _ in range(steps):
            H = Xtr @ A.T                                             # (n, r): the narrow bottleneck
            out = Xtr @ W0.T + s * H @ B.T                            # frozen path + adapter path
            err = out - Ytr
            g_out = 2 * err / err.size
            gB = s * g_out.T @ H                                      # chain rule through B
            gA = s * (g_out @ B).T @ Xtr                              # ... and through A
            opt.step([gA, gB])
        return A, B, s
    
    
    print(f"layer: {d_out} x {d_in} = {d_out * d_in:,} weights (frozen); true task change has rank 2")
    print(f"training examples: {n_train}, validation examples: {n_val}")
    print(f"no fine-tuning (W0 only):  val MSE {mse(W0, Xva, Yva):.4f}")
    print(f"perfect weights (W_task):  val MSE {mse(W_task, Xva, Yva):.4f}   <- noise floor\n")
    
    print(f"{'method':<16}{'trainable':>10}{'% of layer':>12}{'train MSE':>11}{'val MSE':>10}")
    W_full, n_full = train_full()
    print(f"{'full fine-tune':<16}{n_full:>10,}{100.0:>11.1f}%{mse(W_full, Xtr, Ytr):>11.4f}{mse(W_full, Xva, Yva):>10.4f}")
    adapters = {}
    for r in (1, 2, 4, 8):
        A, B, s = train_lora(r)
        adapters[r] = (A, B, s)
        W_eff = W0 + s * B @ A
        n = A.size + B.size
        print(f"{'LoRA r=' + str(r):<16}{n:>10,}{100 * n / W0.size:>11.1f}%{mse(W_eff, Xtr, Ytr):>11.4f}{mse(W_eff, Xva, Yva):>10.4f}")
    
    # Merge: fold the adapter into the weight so inference costs nothing extra.
    A, B, s = adapters[2]
    W_merged = W0 + s * B @ A
    x = Xva[:5]
    unmerged = x @ W0.T + s * (x @ A.T) @ B.T
    gap = float(np.max(np.abs(unmerged - x @ W_merged.T)))
    print(f"\nmerged r=2 adapter: max output difference vs adapter path = {'below 1e-12' if gap < 1e-12 else gap}")
    print(f"rank of learned update B@A: {int(np.linalg.matrix_rank(B @ A))} (can never exceed r)")
    print(f"adapter file size at bf16: {(A.size + B.size) * 2:,} bytes vs full layer {W0.size * 2:,} bytes")
    1. W0 is the frozen weight; delta_true is a rank-2 change (U @ V with inner size 2); W_task is what the new task really needs. make_data adds noise to the targets, like imperfect labels.
    2. class Adam: the optimiser from module 3, written to update parameter arrays in place.
    3. train_full: a trainable matrix D of the full size. The gradient of the mean squared error with respect to the weight is 2 * err.T @ Xtr / err.size.
    4. train_lora(r, alpha=16): A random, B = 0, scale s = alpha / r. The forward pass is the frozen path plus s * (X @ A.T) @ B.T.
    5. gB = s * g_out.T @ H and gA = s * (g_out @ B).T @ Xtr: the chain rule through the two small matrices. Note that gA is zero at the first step because B is zero; B moves first, then A starts learning.
    6. The table prints the trainable parameter count and the train and validation errors; validation uses 1,000 fresh examples.
    7. The merge block computes W_merged = W0 + s * B @ A and confirms the merged layer gives the same outputs as the adapter path, and that the rank of the update is at most r.
    layer: 64 x 64 = 4,096 weights (frozen); true task change has rank 2
    training examples: 48, validation examples: 1000
    no fine-tuning (W0 only):  val MSE 0.0576
    perfect weights (W_task):  val MSE 0.0100   <- noise floor
    
    method           trainable  % of layer  train MSE   val MSE
    full fine-tune       4,096      100.0%     0.0000    0.0568
    LoRA r=1               128        3.1%     0.0273    0.0419
    LoRA r=2               256        6.2%     0.0092    0.0258
    LoRA r=4               512       12.5%     0.0081    0.0311
    LoRA r=8             1,024       25.0%     0.0062    0.0380
    
    merged r=2 adapter: max output difference vs adapter path = below 1e-12
    rank of learned update B@A: 2 (can never exceed r)
    adapter file size at bf16: 512 bytes vs full layer 8,192 bytes

    Full fine-tuning drives the training error to 0.0000 and barely improves validation (0.0576 → 0.0568): 4,096 free numbers and only 48 × 64 noisy targets, so it memorises the noise. LoRA at rank 2, matching the true change, gets the best validation error (0.0258) with 6% of the parameters. Rank 1 is too narrow to express the change; ranks 4 and 8 have spare capacity that starts fitting noise. The low rank is not only cheaper, it acts as a strong regulariser when data is scarce, which is the usual situation in fine-tuning. Real tasks do not have a known true rank, so rank is chosen by trying a few values (8, 16, 32 are common) on validation data.

    LoRA parameter counterInteractive

    Shapes similar to public open-weight models. Choose a size, the rank and which layers get adapters.

    QLoRA: the frozen model in 4 bits

    LoRA removes the memory for gradients and optimiser states of the big model, but the frozen weights still have to sit in GPU memory: 16 GB for 8 billion parameters in bf16. QLoRA (Dettmers et al., 2023, "QLoRA: Efficient Finetuning of Quantized LLMs") stores them in 4 bits instead, cutting that to about 4 GB. Three ingredients:

    • 4-bit NormalFloat (NF4). Weights are split into blocks of 64; each block stores its largest absolute value as a scale and each weight as one of 16 levels. Because trained weights are roughly normally distributed, NF4 places the levels at quantiles of a normal distribution, closer together near zero where most weights are.
    • Double quantisation. The per-block scales are themselves quantised to 8 bits, saving about 0.37 bits per weight.
    • Paged optimisers. Optimiser states can be paged out to CPU memory during rare memory spikes instead of crashing with an out-of-memory error.

    During training each block is dequantised to bf16 on the fly for the matrix multiplication, gradients flow through it to the LoRA adapters (which stay in bf16), and the 4-bit weights never change. The paper reported that QLoRA matched 16-bit LoRA fine-tuning quality on its benchmarks while fitting a 65B model on a single 48 GB GPU. The next script shows the storage side in NumPy.

    # @run
    # quantize_nf4.py: the 4-bit storage trick behind QLoRA, in NumPy.
    # Weights are split into blocks of 64; each block stores one scale (its absolute maximum) and 4-bit codes.
    # We compare two sets of 16 levels: evenly spaced ("int4") and NF4-style levels placed at quantiles of a
    # normal distribution (built the way the QLoRA paper describes, simplified). Then we count the bits per weight.
    from statistics import NormalDist
    
    import numpy as np
    
    rng = np.random.default_rng(0)
    BLOCK = 64
    
    
    def nf4_levels():
        """16 levels: 0 exactly, 7 negative and 8 positive, at normal quantiles, scaled into [-1, 1]."""
        nd = NormalDist()
        offset = 0.9677                                     # keeps the extreme quantiles finite (value from the paper)
        pos = [nd.inv_cdf(p) for p in np.linspace(offset, 0.5, 9)[:-1]]
        neg = [-nd.inv_cdf(p) for p in np.linspace(offset, 0.5, 8)[:-1]]
        levels = np.array(sorted(pos + [0.0] + neg))
        return levels / np.abs(levels).max()
    
    
    INT4 = np.linspace(-1, 1, 16)                           # evenly spaced (no exact zero with 16 levels)
    NF4 = nf4_levels()
    
    
    def quantize(w, levels):
        blocks = w.reshape(-1, BLOCK)
        scale = np.abs(blocks).max(1, keepdims=True)        # one absmax per block
        normed = blocks / scale                             # now in [-1, 1]
        mids = (levels[1:] + levels[:-1]) / 2               # boundaries halfway between neighbouring levels
        codes = np.searchsorted(mids, normed).astype(np.uint8)   # index of the nearest level = the 4-bit code
        return codes, scale
    
    
    def dequantize(codes, scale, levels):
        return (levels[codes] * scale).reshape(-1)
    
    
    # Pretrained weights are roughly normally distributed around 0: simulate a 1024 x 1024 matrix
    w = rng.normal(0, 0.02, size=1024 * 1024)
    print(f"weights: {w.size:,} values, std {float(w.std()):.4f}")
    print("NF4-style levels:", " ".join(f"{x:.3f}" for x in NF4))
    
    for name, levels in [("int4 (even)", INT4), ("NF4-style", NF4)]:
        codes, scale = quantize(w, levels)
        err = dequantize(codes, scale, levels) - w
        rel = float(np.sqrt(np.mean(err ** 2)) / w.std())
        used = np.bincount(codes.reshape(-1), minlength=16) / codes.size
        print(f"{name:<12} relative RMS error {rel:.3f}; least / most used level {used.min():.1%} / {used.max():.1%}")
    
    # Memory per weight. Scales: fp32 (4 bytes) per block of 64, or "double quantised" to 8 bits
    # with one fp32 scale per 256 blocks (the QLoRA paper's numbers).
    plain = 4 + 32 / BLOCK
    double = 4 + 8 / BLOCK + 32 / (BLOCK * 256)
    print(f"\nbits per weight: bf16 16.000, 4-bit + fp32 scales {plain:.3f}, 4-bit + double-quantised scales {double:.3f}")
    for n_params in (8e9, 70e9):
        gb = lambda bits: n_params * bits / 8 / 1e9
        print(f"{n_params / 1e9:.0f}B weights: bf16 {gb(16):6.1f} GB  ->  NF4 + double quant {gb(double):5.1f} GB")
    1. nf4_levels(): 8 positive and 7 negative normal quantiles plus an exact zero, scaled into [-1, 1], built with the standard library's NormalDist().inv_cdf. The printed levels match the published NF4 table to about three decimals.
    2. quantize: reshape into blocks of 64, divide by each block's absolute maximum, then np.searchsorted on the midpoints between levels finds the nearest level's index: a number from 0 to 15, i.e. 4 bits.
    3. dequantize: look up the level and multiply by the block's scale. This is what happens inside every forward pass.
    4. The loop compares evenly spaced levels with NF4 on one million normally distributed weights: error relative to the weights' spread and how evenly the 16 levels are used.
    5. The last block counts bits per weight: 4 bits plus a 32-bit scale per 64 weights is 4.5 bits; with 8-bit scales and one 32-bit scale per 256 blocks it is about 4.127.
    weights: 1,048,576 values, std 0.0200
    NF4-style levels: -1.000 -0.696 -0.525 -0.395 -0.284 -0.185 -0.091 0.000 0.080 0.161 0.246 0.338 0.441 0.563 0.723 1.000
    int4 (even)  relative RMS error 0.101; least / most used level 1.2% / 13.5%
    NF4-style    relative RMS error 0.092; least / most used level 1.7% / 9.2%
    
    bits per weight: bf16 16.000, 4-bit + fp32 scales 4.500, 4-bit + double-quantised scales 4.127
    8B weights: bf16   16.0 GB  ->  NF4 + double quant   4.1 GB
    70B weights: bf16  140.0 GB  ->  NF4 + double quant  36.1 GB

    NF4 has a lower error (0.092 against 0.101 of the weights' spread) and uses its 16 levels more evenly (no level below 1.7% or above 9.2%), which is what you want from a code: no wasted values. An 8B model's weights drop from 16 GB to about 4.1 GB, and a 70B model's from 140 GB to about 36 GB. The cost is a small loss of precision in the frozen model, which the LoRA adapters, trained against the quantised weights, partly compensate for. Module 11 (lesson 11.2) covers quantisation for inference.

    A real QLoRA run

    The script below fine-tunes an open-weight chat model on the train.jsonl and val.jsonl files of lesson 10.3 with the Hugging Face transformers, peft and bitsandbytes libraries, using a plain PyTorch loop so every step is visible. It needs an NVIDIA GPU and those packages; our tests only check that it compiles, they do not run it. The APIs used are long-standing ones, but libraries change; if a call fails, check the current documentation for your installed version.

    # qlora_train.py: fine-tune an open-weight chat model with QLoRA on one GPU.
    # Needs: pip install torch transformers peft bitsandbytes accelerate   (and an NVIDIA GPU with ~16-24 GB)
    # NOT executed by the course tests. It uses long-standing APIs of transformers / peft / bitsandbytes, but
    # libraries change: if a call fails, check the current docs of the version you installed.
    #
    # Input: train.jsonl and val.jsonl from instruction_dataset.py (one {"messages": [...]} object per line).
    # Output: a LoRA adapter folder (tens of MB for a 1-2B model) that you load on top of the same base model.
    import json
    import math
    import random
    
    import torch
    from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
    from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
    
    BASE = "Qwen/Qwen2.5-1.5B-Instruct"   # any chat model with a chat template; check its licence first
    MAX_LEN, EPOCHS, LR, BATCH, ACCUM = 1024, 3, 2e-4, 4, 4
    torch.manual_seed(0)
    random.seed(0)
    
    # 1. Load the frozen base model in 4-bit NF4 (QLoRA), computing in bf16.
    bnb = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4",
                             bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype=torch.bfloat16)
    tok = AutoTokenizer.from_pretrained(BASE)
    if tok.pad_token is None:
        tok.pad_token = tok.eos_token
    model = AutoModelForCausalLM.from_pretrained(BASE, quantization_config=bnb, device_map="auto")
    model = prepare_model_for_kbit_training(model)        # enables gradient checkpointing, casts norms to fp32
    
    # 2. Add LoRA adapters to the attention and MLP projections. Only these are trained.
    lora = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05, task_type="CAUSAL_LM",
                      target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"])
    model = get_peft_model(model, lora)
    model.print_trainable_parameters()                    # typically well under 2% of all parameters
    
    
    # 3. Tokenise with the model's own chat template; only assistant tokens carry loss (labels -100 elsewhere).
    def encode(messages):
        ids, labels = [], []
        for i, m in enumerate(messages):
            # Render the conversation up to message i and keep only the new part, so every token has a known owner.
            before = tok.apply_chat_template(messages[:i], tokenize=False) if i else ""
            upto = tok.apply_chat_template(messages[:i + 1], tokenize=False)
            assert upto.startswith(before), "this chat template is not prefix-stable; mask by searching for markers"
            piece = tok(upto[len(before):], add_special_tokens=False)["input_ids"]
            ids += piece
            labels += piece if m["role"] == "assistant" else [-100] * len(piece)
        return ids[:MAX_LEN], labels[:MAX_LEN]
    
    
    def load(path):
        with open(path, encoding="utf-8") as f:
            return [encode(json.loads(line)["messages"]) for line in f if line.strip()]
    
    
    train, val = load("train.jsonl"), load("val.jsonl")
    
    
    def batches(data, shuffle):
        order = list(range(len(data)))
        if shuffle:
            random.shuffle(order)
        for s in range(0, len(order), BATCH):
            chunk = [data[i] for i in order[s:s + BATCH]]
            width = max(len(ids) for ids, _ in chunk)
            ids = [x + [tok.pad_token_id] * (width - len(x)) for x, _ in chunk]
            lab = [y + [-100] * (width - len(y)) for _, y in chunk]
            att = [[1] * len(x) + [0] * (width - len(x)) for x, _ in chunk]
            yield (torch.tensor(ids).to(model.device), torch.tensor(lab).to(model.device),
                   torch.tensor(att).to(model.device))
    
    
    @torch.no_grad()
    def val_loss():
        model.eval()
        total, n = 0.0, 0
        for ids, lab, att in batches(val, shuffle=False):
            total += model(input_ids=ids, attention_mask=att, labels=lab).loss.item()
            n += 1
        model.train()
        return total / max(n, 1)
    
    
    # 4. A plain training loop: AdamW on the adapter weights, warm-up then cosine decay, gradient accumulation.
    params = [p for p in model.parameters() if p.requires_grad]
    opt = torch.optim.AdamW(params, lr=LR, weight_decay=0.0)
    total_steps = EPOCHS * math.ceil(len(train) / BATCH / ACCUM)
    warmup = max(1, total_steps // 20)
    sched = torch.optim.lr_scheduler.LambdaLR(
        opt, lambda s: min(1.0, (s + 1) / warmup) * 0.5 * (1 + math.cos(math.pi * min(1.0, s / total_steps))))
    
    best = float("inf")
    print(f"start: val loss {val_loss():.3f}")
    model.train()
    for epoch in range(EPOCHS):
        for step, (ids, lab, att) in enumerate(batches(train, shuffle=True)):
            loss = model(input_ids=ids, attention_mask=att, labels=lab).loss / ACCUM
            loss.backward()
            if (step + 1) % ACCUM == 0:
                torch.nn.utils.clip_grad_norm_(params, 1.0)
                opt.step()
                sched.step()
                opt.zero_grad()
        v = val_loss()
        print(f"epoch {epoch + 1}: val loss {v:.3f}")
        if v < best:                                       # early stopping by keeping the best epoch
            best = v
            model.save_pretrained("adapter-best")          # saves only the LoRA weights + adapter_config.json
    
    # 5. Later: load the base model, then the adapter, and (optionally) merge for faster inference:
    #    from peft import PeftModel
    #    model = PeftModel.from_pretrained(AutoModelForCausalLM.from_pretrained(BASE, torch_dtype=torch.bfloat16), "adapter-best")
    #    model = model.merge_and_unload()                  # merge into a bf16 copy, not into the 4-bit weights
    1. BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype=torch.bfloat16): the three QLoRA settings plus the compute precision used after dequantisation.
    2. prepare_model_for_kbit_training(model): enables gradient checkpointing (lesson 10.6) and keeps a few sensitive layers such as norms in higher precision.
    3. LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05, target_modules=[...]): rank 16, scale 2, a little dropout on the adapter input, and adapters on all seven linear projections of each block. The module names are those used by Llama-, Qwen- and Mistral-style models; other architectures name them differently (print model to see).
    4. encode(messages): renders the conversation with the model's own chat template one message at a time, so each token is known to belong to a role, and sets labels to -100 for everything except assistant messages. The assert stops if the template is not prefix-stable.
    5. batches: pads each batch to its longest record, with padded labels set to -100 and an attention mask of 0 so padding is ignored.
    6. The loop is the PyTorch step from lesson 10.4: AdamW on adapter parameters only, warm-up then cosine decay, gradient accumulation and clipping, validation loss after each epoch, and model.save_pretrained("adapter-best") on improvement (early stopping by checkpoint).
    7. The final comment shows loading the adapter with PeftModel.from_pretrained and merge_and_unload() into a bf16 copy of the base model, not into the 4-bit one.

    Higher-level trainers exist (for example TRL's SFTTrainer and DPOTrainer, which accept a LoRA config), and tools such as Axolotl, LLaMA-Factory and Unsloth wrap the same steps in configuration files. They save time once you know what they do; their options change between versions, so follow their current docs.

    DPO with LoRA (promised in lesson 6.5) works the same way: the policy is the base model plus a trainable adapter, and the reference model needed by the DPO loss is simply the base model with the adapter switched off, so you do not need a second copy of the weights in memory.

    Choosing rank and targets, and LoRA's relatives

    Rank and targets. The original LoRA paper adapted only the query and value projections and found small ranks sufficient for its tasks. Later practice, including the QLoRA paper, found that adapting all linear layers matters more than a high rank. A reasonable start is rank 16 with alpha 16 to 32 on all linear layers; raise the rank for tasks that need more new behaviour (a new language, a lot of code), lower it for style changes.

    Learning less, forgetting less. Biderman et al. (2024, "LoRA Learns Less and Forgets Less") compared LoRA with full fine-tuning on code and maths with large datasets: full fine-tuning learned the target domain better, while LoRA kept more of the base model's other abilities. For typical small fine-tuning datasets the gap is smaller, and LoRA's lower forgetting is often what you want.

    Relatives. rsLoRA changes the scale to α/r so higher ranks train stably; DoRA splits each weight into a magnitude and a direction and adapts them separately; LoRA+ uses a larger learning rate for B than for A. Each is a small change to the same idea. Prefix tuning and prompt tuning train a few virtual tokens instead of weight updates; they use even fewer parameters but are generally weaker on hard tasks.

    Serving many adapters. Because adapters are small and the base is shared, inference servers can host hundreds of LoRA adapters on one base model and choose one per request (multi-LoRA serving) Industry practice.

    Common mistakes and debugging tips

    "trainable params: 0" or an error about target modules

    The names in target_modules do not exist in this architecture (some models call their projections query_key_value or c_attn).

    Fix: print(model) and copy the names of the linear layers; check print_trainable_parameters() shows a sensible small percentage before training.

    Using an adapter with a different base model

    An adapter trained on one model loads without error on a similar-looking model of another version, and output is garbage.

    Fix: an adapter is only valid for the exact base weights it was trained on; store the base model id and revision in the adapter folder (peft writes adapter_config.json) and check it.

    Merging into the 4-bit weights

    Merging LoRA into quantised weights and re-quantising adds a second rounding error and can noticeably change behaviour.

    Fix: merge into a bf16 copy of the base model, then quantise the merged model for deployment if needed, and evaluate after each step.

    A LoRA learning rate copied from full fine-tuning

    With 2e-5, LoRA adapters barely move, and "fine-tuning made no difference".

    Fix: LoRA usually needs a roughly ten times higher rate (around 1e-4 to 2e-4 as a start); confirm with a short sweep on validation loss.

    Key takeaways

    • LoRA freezes each weight and trains a low-rank update BA scaled by α/r, often under 1% of the parameters.
    • B=0 at the start means training begins from the original model; merging after training makes inference cost nothing extra.
    • Low rank is also a regulariser: with little data it can beat full fine-tuning.
    • QLoRA keeps the frozen model in 4-bit NF4 (about 4.1 bits per weight with double quantisation), which is what fits 8B-class fine-tuning on one consumer GPU.

    Exercise: when the true change has a higher rank

    In lora_numpy.py, change the true task change to rank 6 (U of shape (d_out, 6) and V of shape (6, d_in)) and run again. Which rank wins now? Then double the training examples to 96. What changes for full fine-tuning?

    Hint

    Predict first: a rank-r adapter can represent any change of rank up to r, and no more. More data makes memorising noise harder for every method.

    Show a solution

    Edit two lines: U = rng.normal(size=(d_out, 6)) and V = rng.normal(size=(6, d_in)). With 48 examples the validation errors become: full 0.0811, rank 1 0.1200, rank 2 0.0948, rank 4 0.0756, rank 8 0.0541. Ranks 1 and 2 can no longer express the change; rank 8, the smallest tested rank that is at least 6, wins. With n_train = 96 there are more examples than unknowns per output row (64), so full fine-tuning stops fitting the training set perfectly (train 0.0033) and its validation error drops from 0.0811 to 0.0326. Rank 8 still wins (0.0132), but the gap narrows. The general lesson: the right rank depends on how much the task really changes, and full fine-tuning becomes more competitive as data grows.

    Check your understanding

    Why is B initialised to zero in LoRA?

    1. To save memory
    2. So that BA=0 and the adapted model starts exactly as the original
    3. Because A is never trained
    With B = 0 the adapter adds nothing at step 0, so training starts from the pretrained behaviour. A is random so that B's gradient is not zero; both are trained.

    A layer is 4,096 × 4,096. How many parameters does a rank-8 LoRA adapter on it have?

    1. 65,536
    2. 16,777,216
    3. 32,768
    A has 8 × 4,096 and B has 4,096 × 8 numbers: 8 × (4,096 + 4,096) = 65,536, about 0.4% of the 16.8 million in the full matrix.

    What does QLoRA store in 4 bits?

    1. The LoRA adapters
    2. The gradients
    3. The frozen base model weights; adapters and computation stay in 16-bit
    Only the frozen base is quantised (NF4). It is dequantised block by block for each matrix multiplication; the trainable adapters and their optimiser states stay in higher precision so training remains accurate.

    Lesson 10.6Module 10: Fine-tuning and training

    GPU and VRAM requirements

    • ⏱ 14 min read
    • Advanced

    Learning objectives

    • List what occupies GPU memory during inference and training: weights, gradients, optimiser states, activations, KV cache and overhead.
    • Estimate memory from bytes per parameter: about 2 for bf16 inference, about 16 for full fine-tuning with Adam, a little over 2 for LoRA and about 0.5 for QLoRA.
    • Compute the KV cache size for a given context length and the effect of gradient checkpointing on activations.
    • Know the techniques that make a job fit (smaller batch with accumulation, checkpointing, quantisation, 8-bit optimisers, sharding, offloading) and what each costs.

    "CUDA out of memory" is the error every fine-tuning beginner meets first. GPU memory, called VRAM, is the hard limit of the work: a GPU can be slow and still finish, but if the job does not fit, it does not start. The good news is that memory is predictable. With a few multiplications you can tell, before renting anything, whether a job fits on a 24 GB card, needs an 80 GB one, or needs several.

    Analogy: packing a removal van

    Before moving house you estimate whether everything fits in the van: the big furniture (the weights), the boxes you will need to unpack on arrival (gradients and optimiser states), and the things you carry around while loading (activations and the KV cache). Some furniture can be taken apart to save space (quantisation), some boxes can go in a second trip (offloading to CPU), and with two vans you split the load (sharding across GPUs). Measure first, then choose the van.

    What uses the memory

    ItemInferenceTrainingSize
    Weightsyesyesparameters × bytes per value (fp32 4, bf16 2, int8 1, 4-bit about 0.5)
    Gradientsnoyes, for trainable weightstrainable parameters × 2 (bf16)
    Optimiser statesnoyes, for trainable weightsAdam: two fp32 moments (8 bytes) plus usually an fp32 master copy of the weights (4 bytes)
    Activationstiny (one layer at a time)large: kept for the backward passgrows with batch × sequence length × hidden size × layers
    KV cacheyes, grows with contextno (whole sequences are processed at once)2 × layers × KV heads × head size × tokens × 2 bytes
    OverheadyesyesCUDA context, library workspaces, fragmentation: often 0.5 to 2 GB; keep 10–20% headroom

    From this table come four rules of thumb you will use constantly:

    • Inference in bf16: about 2 bytes per parameter, plus the KV cache. An 8B model needs about 16 GB.
    • Full fine-tuning with Adam in mixed precision: about 16 bytes per parameter (2 weights + 2 gradients + 4 master copy + 8 Adam moments), plus activations. An 8B model needs about 128 GB before activations, more than any single GPU in this list.
    • LoRA: the frozen bf16 weights (2 bytes per parameter) plus about 16 bytes per adapter parameter, which is tiny, plus activations.
    • QLoRA: about 0.5 bytes per parameter for the 4-bit weights plus the same small adapter cost and activations.

    The KV cache and activations

    During generation the model stores the keys and values of every previous token in every layer, so it does not recompute them (lesson 6.8). Its size grows linearly with the context:

    KV bytes=2×nlayers×nkv heads×dhead×tokens×batch×bytes per value

    In words: one key and one value vector (the 2) per KV head, per layer, per token. For an 8B-class model with 32 layers, 8 KV heads of size 128 and bf16 values that is 128 KB per token: 4.3 GB for a 32,768-token context, 17 GB for 131,072 tokens, more than the weights.

    The 8 KV heads (instead of 32) come from grouped-query attention, which shares each key/value head among several query heads precisely to shrink this cache. In training, the equivalent memory hog is activations: every layer's intermediate results are kept for the backward pass. Gradient checkpointing keeps only each layer's input and recomputes the rest during the backward pass, trading about 30% more compute for a large memory saving.

    A memory estimator

    The script applies these rules to three model shapes similar to public open-weight configurations and reports the smallest common GPU setup that fits with 10% headroom.

    # @run
    # vram_estimator.py: rough GPU memory (VRAM) estimates for running and fine-tuning a decoder-only transformer.
    # Rules of thumb only. Real usage also depends on the framework, kernels (FlashAttention), fragmentation and
    # the CUDA context (often 0.5-1 GB), so keep 10-20% headroom. All sizes in GB (1e9 bytes).
    GB = 1e9
    
    # Shapes similar to public open-weight model configs (layers, hidden size, KV heads, head size).
    MODELS = {
        "1B":  dict(params=1.2e9, layers=16, hidden=2048, kv_heads=8, head_dim=64),
        "8B":  dict(params=8.0e9, layers=32, hidden=4096, kv_heads=8, head_dim=128),
        "70B": dict(params=70.6e9, layers=80, hidden=8192, kv_heads=8, head_dim=128),
    }
    
    
    def kv_cache(m, seq, batch, bytes_per=2):
        """Keys + values for every layer and every token: 2 x layers x kv_heads x head_dim x tokens."""
        return 2 * m["layers"] * m["kv_heads"] * m["head_dim"] * seq * batch * bytes_per / GB
    
    
    def activations(m, seq, batch, checkpointing):
        """Very rough training activations at 16-bit with FlashAttention: ~34 bytes per token per hidden unit
        per layer (Korthikanti et al., 2022, attention-score term removed). With gradient checkpointing only
        each layer's input (2 bytes) is kept, plus one layer being recomputed."""
        per_layer = 34 * seq * batch * m["hidden"]
        if checkpointing:
            return (2 * seq * batch * m["hidden"] * m["layers"] + per_layer) / GB
        return per_layer * m["layers"] / GB
    
    
    def lora_params(m, r):
        """LoRA on the 4 attention projections + 3 MLP projections of every layer (approximate shapes)."""
        h, kv = m["hidden"], m["kv_heads"] * m["head_dim"]
        ffn = int(3.5 * h)                                    # typical SwiGLU width
        shapes = [(h, h), (h, kv), (h, kv), (h, h), (h, ffn), (h, ffn), (ffn, h)]
        return m["layers"] * sum(r * (a + b) for a, b in shapes)
    
    
    def estimate(m, mode, seq=2048, batch=1, r=16):
        P = m["params"]
        if mode == "inference bf16":
            parts = {"weights": 2 * P / GB, "KV cache": kv_cache(m, seq, batch)}
        elif mode == "inference 4-bit":
            parts = {"weights": 0.56 * P / GB, "KV cache": kv_cache(m, seq, batch)}
        elif mode == "full fine-tune":
            # bf16 weights + bf16 grads + fp32 master copy + Adam m and v (fp32) = 2 + 2 + 4 + 4 + 4 = 16 bytes/param
            parts = {"weights+grads": 4 * P / GB, "optimizer": 12 * P / GB,
                     "activations": activations(m, seq, batch, True)}
        elif mode in ("LoRA", "QLoRA"):
            n = lora_params(m, r)
            parts = {"weights": (2 if mode == "LoRA" else 0.52) * P / GB,
                     "adapters+optim": 16 * n / GB,
                     "activations": activations(m, seq, batch, True)}
        return parts, sum(parts.values())
    
    
    GPUS = [("24 GB", 24), ("48 GB", 48), ("80 GB", 80), ("2 x 80 GB", 160), ("8 x 80 GB", 640)]   # several GPUs = sharded
    
    
    def fits(total):
        for name, cap in GPUS:
            if total * 1.1 <= cap:                            # 10% headroom
                return name
        return "multi-node"
    
    
    print("Rough VRAM, sequence 2,048 tokens, batch 1, LoRA rank 16, gradient checkpointing on\n")
    print(f"{'model':<5} {'mode':<16}{'total GB':>9}  {'smallest fit':<13} breakdown")
    for name, m in MODELS.items():
        for mode in ("inference bf16", "inference 4-bit", "full fine-tune", "LoRA", "QLoRA"):
            parts, total = estimate(m, mode)
            detail = ", ".join(f"{k} {v:.1f}" for k, v in parts.items())
            print(f"{name:<5} {mode:<16}{total:>9.1f}  {fits(total):<13} {detail}")
        print()
    
    m = MODELS["8B"]
    print(f"8B LoRA r=16 trains {lora_params(m, 16) / 1e6:.0f}M parameters "
          f"({100 * lora_params(m, 16) / m['params']:.2f}% of the model)")
    print("8B KV cache at bf16 for one sequence:", ", ".join(f"{s:,} tokens {kv_cache(m, s, 1):.2f} GB"
                                                         for s in (2048, 32768, 131072)))
    print("8B training activations, 4 sequences of 4,096 tokens: "
          f"{activations(m, 4096, 4, False):.1f} GB without checkpointing, {activations(m, 4096, 4, True):.1f} GB with")
    1. MODELS: parameter count, layers, hidden size, KV heads and head size, the numbers that decide memory. The shapes resemble published configs of 1B, 8B and 70B open models.
    2. kv_cache(m, seq, batch): the formula above, in GB.
    3. activations(m, seq, batch, checkpointing): a rough 34 bytes per token per hidden unit per layer for a standard block at 16-bit with FlashAttention, from the analysis in Korthikanti et al. (2022); with checkpointing only 2 bytes per token per hidden unit per layer (the layer inputs) plus one full layer being recomputed. Real numbers vary with the architecture and kernels.
    4. lora_params(m, r): r×(din+dout) for the seven linear projections of every layer, with a typical gated-MLP width of 3.5 × hidden.
    5. estimate(m, mode): adds up the parts for each mode, using 16 bytes per trainable parameter for weights, gradients and Adam, and 0.52 bytes per parameter for 4-bit weights with their scales.
    6. fits(total): the first setup in GPUS whose capacity covers the total plus 10%. Several GPUs only help if the framework shards the model across them.
    Rough VRAM, sequence 2,048 tokens, batch 1, LoRA rank 16, gradient checkpointing on
    
    model mode             total GB  smallest fit  breakdown
    1B    inference bf16        2.5  24 GB         weights 2.4, KV cache 0.1
    1B    inference 4-bit       0.7  24 GB         weights 0.7, KV cache 0.1
    1B    full fine-tune       19.5  24 GB         weights+grads 4.8, optimizer 14.4, activations 0.3
    1B    LoRA                  2.8  24 GB         weights 2.4, adapters+optim 0.2, activations 0.3
    1B    QLoRA                 1.1  24 GB         weights 0.6, adapters+optim 0.2, activations 0.3
    
    8B    inference bf16       16.3  24 GB         weights 16.0, KV cache 0.3
    8B    inference 4-bit       4.7  24 GB         weights 4.5, KV cache 0.3
    8B    full fine-tune      128.8  2 x 80 GB     weights+grads 32.0, optimizer 96.0, activations 0.8
    8B    LoRA                 17.5  24 GB         weights 16.0, adapters+optim 0.7, activations 0.8
    8B    QLoRA                 5.7  24 GB         weights 4.2, adapters+optim 0.7, activations 0.8
    
    70B   inference bf16      141.9  2 x 80 GB     weights 141.2, KV cache 0.7
    70B   inference 4-bit      40.2  48 GB         weights 39.5, KV cache 0.7
    70B   full fine-tune     1132.9  multi-node    weights+grads 282.4, optimizer 847.2, activations 3.3
    70B   LoRA                147.8  8 x 80 GB     weights 141.2, adapters+optim 3.3, activations 3.3
    70B   QLoRA                43.3  48 GB         weights 36.7, adapters+optim 3.3, activations 3.3
    
    8B LoRA r=16 trains 42M parameters (0.52% of the model)
    8B KV cache at bf16 for one sequence: 2,048 tokens 0.27 GB, 32,768 tokens 4.29 GB, 131,072 tokens 17.18 GB
    8B training activations, 4 sequences of 4,096 tokens: 73.0 GB without checkpointing, 6.6 GB with

    The table is the practical map of this module. An 8B model can be used on a 24 GB card in bf16 (just) and comfortably in 4-bit; it can be fine-tuned with LoRA (17.5 GB) or QLoRA (5.7 GB) on that same card, but full fine-tuning needs about 129 GB, so at least two 80 GB GPUs with sharding. A 70B model needs 4-bit even for single-GPU inference, QLoRA puts its fine-tuning within reach of one 48 GB card (as the QLoRA paper showed for 65B), and full fine-tuning needs more than a whole 8-GPU server. The last lines show why long contexts are costly at inference and why checkpointing is on by default in fine-tuning scripts: 73 GB of activations become 6.6 GB.

    VRAM calculatorInteractive

    The same rules as vram_estimator.py. Rough estimates: real use varies by framework and kernels.

    Which GPU, roughly

    Approximate memory of common GPU classes as of 2026 (models and prices change; check current specifications):

    ClassMemoryRealistic for
    Laptop / older consumer GPU6–12 GBinference of small 4-bit models; QLoRA of 1B–3B models
    High-end consumer (RTX 4090 / 5090 class)24–32 GBQLoRA up to roughly 14B (tight around 30B); LoRA of 7B–8B; 8B inference in bf16
    Workstation (RTX 6000 class, L40S)48 GBQLoRA of 70B with short sequences; LoRA of 14B
    Data-centre (A100 / H100)80 GBLoRA of 30B-class models; QLoRA of 70B with room; one shard of larger jobs
    Newer data-centre (H200, B200 class)about 141–192 GBlarger single-GPU jobs; usually used in 8-GPU servers
    Apple silicon Macs (unified memory)16–192 GB sharedinference of large quantised models (for example with Ollama or MLX); slower training, mainly small LoRA jobs

    Memory is not the only spec. Memory bandwidth limits how fast tokens are generated (every token reads all weights), and compute (TFLOP/s in bf16) limits training speed, the subject of the next lesson.

    Making a job fit

    • Smaller micro-batch, more accumulation (lesson 10.4): activations shrink, the effective batch stays the same, steps get slower.
    • Shorter sequences: set the maximum from your data's 95th percentile; activations scale with it.
    • Gradient checkpointing: big activation savings for about 30% more compute.
    • Quantised base (QLoRA): 4× smaller frozen weights for a small quality and speed cost.
    • 8-bit or paged optimisers: Adam's states in 8 bits cut 12 bytes per trainable parameter to about 6; matters for full fine-tuning.
    • Sharding across GPUs (ZeRO in DeepSpeed, FSDP in PyTorch): each GPU holds a slice of the weights, gradients and optimiser states.
    • CPU offloading: keep optimiser states in CPU memory; it works but is much slower.
    ZeRO stages, measuring real usage, and GB versus GiB

    ZeRO (Rajbhandari et al., 2019) removes redundancy in data-parallel training. Plain data parallelism keeps a full copy of everything on each of N GPUs. Stage 1 shards the optimiser states (12 of the 16 bytes per parameter) across the GPUs, stage 2 also shards gradients, and stage 3 also shards the weights themselves, gathering each layer's weights just before it is used. With stage 3 the 16 bytes per parameter become roughly 16/N per GPU, which is how an 8B full fine-tune fits on two 80 GB GPUs. PyTorch's FSDP implements the same idea.

    Measure, then trust. In PyTorch, torch.cuda.max_memory_allocated() after a few training steps gives the peak allocated by tensors; nvidia-smi shows what the process reserved, which is larger because the caching allocator keeps freed blocks. Run a few steps with your longest sequence first: memory peaks on the longest batch, and an out-of-memory error at hour three on one long example is a classic.

    Units. GPU vendors quote memory in GiB-ish marketing units while scripts often divide by 1e9. 80 GB of HBM is about 80 × 230 bytes = 85.9 × 109 bytes. The estimator uses 109, which errs on the safe side. The differences are smaller than the uncertainty of the activation estimate, but they explain why "exactly fits" calculations fail.

    Common mistakes and debugging tips

    Forgetting the optimiser

    "The model is 16 GB and my GPU has 24 GB, so I can fine-tune it." For full fine-tuning, Adam and the gradients add about 112 GB more.

    Fix: count bytes per trainable parameter (about 16 with Adam in mixed precision) or switch to LoRA/QLoRA, where only the adapters carry these costs.

    Out of memory at evaluation or on one long example

    Training runs fine for hours, then crashes on a long record or during generation in the evaluation step, where the KV cache grows.

    Fix: cap sequence length in the data, sort or bucket by length, test the longest batch first, and use a smaller batch for evaluation generation.

    Long context forgotten in inference budgets

    An 8B model "fits in 16 GB", then a 128k-token request needs another 17 GB of KV cache, and several concurrent users multiply that.

    Fix: budget KV cache per concurrent request at your maximum context; consider KV cache quantisation or a lower maximum context (module 11 covers serving).

    Key takeaways

    • Bytes per parameter: about 2 for bf16 inference, about 16 for full fine-tuning with Adam, about 2 plus small change for LoRA, about 0.5 plus small change for QLoRA.
    • The KV cache grows with context and batch and can exceed the weights; activations grow with batch × sequence and are cut by checkpointing.
    • 8B-class fine-tuning fits a 24 GB GPU with LoRA or QLoRA; 70B QLoRA fits 48–80 GB; full fine-tuning needs several GPUs with sharding.
    • Estimate first, then measure the peak with your longest batch.

    Exercise: plan three jobs

    Using the estimator (add a model shape if needed) or the calculator above, decide the smallest GPU setup for: 1) QLoRA of a 14B-class model (48 layers, hidden 5,120, 8 KV heads of 128, 14.8B parameters) at 4,096 tokens; 2) serving an 8B model in bf16 to 4 users at once, each with a 32,768-token context; 3) full fine-tuning of a 1B model at 2,048 tokens, batch 8, with and without checkpointing.

    Hint

    Add an entry to MODELS and call estimate(m, mode, seq=..., batch=...). For job 2, the KV cache is per sequence, times 4.

    Show a solution
    MODELS["14B"] = dict(params=14.8e9, layers=48, hidden=5120, kv_heads=8, head_dim=128)
    for name, mode, seq, batch in [("14B", "QLoRA", 4096, 1), ("8B", "inference bf16", 32768, 4),
                                   ("1B", "full fine-tune", 2048, 8)]:
        parts, total = estimate(MODELS[name], mode, seq=seq, batch=batch)
        print(name, mode, f"{total:.1f} GB", fits(total))

    1) About 11.7 GB (7.7 weights, 1.3 adapters and optimiser, 2.7 activations): a 24 GB card is plenty. 2) Weights 16 GB plus 4 × 4.3 GB of KV cache, about 33 GB: a 48 GB card, not a 24 GB one. 3) About 21.4 GB with checkpointing (16 bytes × 1.2B = 19.2 GB plus 2.2 GB of activations), which fits 24 GB only barely; without checkpointing activations(m, 2048, 8, False) is about 18 GB, about 37.5 GB in total: a 48 GB card. These are estimates: confirm with a short real run.

    Check your understanding

    Roughly how much memory does full fine-tuning of an 8B model with Adam in mixed precision need, before activations?

    1. 16 GB
    2. About 128 GB
    3. About 4 GB
    About 16 bytes per parameter: 2 (bf16 weights) + 2 (gradients) + 4 (fp32 master weights) + 8 (Adam's two moments). 16 GB is only the bf16 weights; 4 GB is the 4-bit weights used by QLoRA.

    What does gradient checkpointing trade?

    1. Accuracy for speed
    2. Disk space for GPU memory
    3. Extra compute (recomputing activations in the backward pass) for much less activation memory
    Only layer inputs are stored; the rest is recomputed when needed during backpropagation. Results are the same, training takes roughly a third longer, and activation memory drops sharply.

    Why can the KV cache become larger than the model's weights?

    1. It grows with every token of context and with every concurrent sequence, while the weights are fixed
    2. Because it is stored in fp32
    3. Because it holds a copy of the weights for each user
    Each token adds keys and values in every layer. At long contexts and several concurrent users, this per-token cost adds up past the fixed size of the weights.

    Lesson 10.7Module 10: Fine-tuning and training

    Training costs and realistic hardware requirements

    • ⏱ 13 min read
    • Intermediate

    Learning objectives

    • Estimate training compute with the rule of thumb of about 6 × parameters × tokens floating-point operations.
    • Turn compute into wall-clock time and money using peak GPU speed, utilisation (MFU) and rental prices.
    • Place real jobs on a ladder from a laptop to a frontier cluster, with honest, dated orders of magnitude.
    • Name the hidden costs (experiments, failures, data, evaluation, people) and compare training with using an API.

    Lesson 10.6 answered "does it fit?". This lesson answers "how long, and how much?". Both questions have surprisingly simple first answers, and both are often answered wrongly by orders of magnitude in either direction: people overestimate what a LoRA fine-tune costs (a few dollars) and underestimate what pretraining a capable model from scratch costs (millions to hundreds of millions). Lesson 3.6 promised a realistic account of what you can train yourself; here it is.

    Analogy: a road trip budget

    To budget a road trip you need the distance, the car's speed and the price of fuel, and you know the car will not drive at top speed the whole way: traffic, stops and detours. Training is the same calculation. The distance is the number of operations the job needs, the car's top speed is the GPU's peak throughput, the realistic average speed is a fraction of that, and fuel is the hourly rental price. And as on any trip, the planned route is never the whole bill: wrong turns (failed runs) and test drives (experiments) cost too.

    How much computation: 6 × N × D

    For a dense transformer, the forward pass costs about 2 floating-point operations (one multiply, one add) per parameter per token: each weight is used once for every token. The backward pass costs about twice that, because it computes gradients with respect to both the activations and the weights. So training costs about 6 operations per parameter per token, a rule popularised by the scaling-law papers (Kaplan et al., 2020; Hoffmann et al., 2022):

    training FLOPs≈6×N×D

    In words: six times the number of parameters N times the number of training tokens D. An 8-billion-parameter model trained on 1 billion tokens needs about 6 × 8×10⁹ × 10⁹ = 4.8×10¹⁹ operations. Attention over long sequences adds a little more; the rule ignores it.

    With LoRA, the frozen weights need no weight gradients, so the backward pass costs about half as much: roughly 4 × N × D in total. Gradient checkpointing adds back about one extra forward pass. For a rough budget these details matter less than the next factor.

    From operations to hours

    A GPU's datasheet gives a peak throughput, for example around 989 TFLOP/s (10¹² operations per second) in dense bf16 for an H100 SXM. Real training reaches only a fraction of that: data loading, communication between GPUs, memory-bound operations and small matrices all waste time. The fraction is called model FLOPs utilisation (MFU). Well-tuned large training runs report roughly 35–50%; a fine-tuning script on one consumer GPU with small batches is often at 10–30% Industry practice.

    time≈6NDGPUs×peak FLOP/s×MFU,cost≈time×GPUs×price per GPU-hour

    In words: divide the work by the useful speed of all GPUs together to get wall-clock time; multiply time by the number of GPUs and the hourly price to get the compute bill.

    A cost calculator

    The script applies these formulas to six jobs, from a QLoRA run on a gaming GPU to pretraining a 70B model, with GPU speeds and rental prices that are rough public figures as of 2026. Treat every output as an order of magnitude, not a quote.

    # @run
    # cost_calculator.py: back-of-the-envelope training time and cost.
    # Rule of thumb: training a dense transformer costs about 6 x N x D floating-point operations
    # (N parameters, D training tokens: ~2ND forward + ~4ND backward). LoRA skips the weight gradients of
    # the frozen model, so it costs roughly 4ND. Real GPUs reach only part of their peak speed (MFU).
    # GPU speeds and prices are APPROXIMATE public figures as of 2026; check current numbers before you budget.
    
    GPUS = {   # name: (peak dense bf16 TFLOP/s, approximate rental price in USD per GPU-hour, as of 2026)
        "RTX 4090 (24 GB)": (165, 0.50),
        "A100 (80 GB)": (312, 1.50),
        "H100 (80 GB)": (989, 2.50),
    }
    
    JOBS = [   # (description, parameters N, tokens D, FLOPs per parameter per token, GPU, number of GPUs, MFU)
        ("QLoRA 8B, 3 epochs x 5M tokens", 8e9, 15e6, 4, "RTX 4090 (24 GB)", 1, 0.25),
        ("LoRA 8B, 3 epochs x 50M tokens", 8e9, 150e6, 4, "A100 (80 GB)", 1, 0.35),
        ("full fine-tune 8B, 1B tokens", 8e9, 1e9, 6, "H100 (80 GB)", 8, 0.40),
        ("pretrain 1B on 20B tokens", 1e9, 20e9, 6, "H100 (80 GB)", 8, 0.40),
        ("pretrain 8B on 15T tokens", 8e9, 15e12, 6, "H100 (80 GB)", 1024, 0.40),
        ("pretrain 70B on 15T tokens", 70e9, 15e12, 6, "H100 (80 GB)", 4096, 0.40),
    ]
    
    
    def human_time(seconds):
        for unit, size in (("days", 86400), ("hours", 3600), ("min", 60)):
            if seconds >= size:
                return f"{seconds / size:.1f} {unit}"
        return f"{seconds:.0f} s"
    
    
    def money(x):
        if x >= 1e6:
            return f"${x / 1e6:.1f}M"
        if x >= 1e3:
            return f"${x / 1e3:.1f}k"
        return f"${x:.2f}"
    
    
    print(f"{'job':<33}{'FLOPs':>9}{'GPUs':>6}{'wall time':>12}{'GPU-hours':>11}{'cost':>9}")
    for desc, n, d, k, gpu, count, mfu in JOBS:
        flops = k * n * d
        peak, price = GPUS[gpu]
        speed = count * peak * 1e12 * mfu                    # useful FLOP/s across all GPUs
        seconds = flops / speed
        gpu_hours = seconds * count / 3600
        print(f"{desc:<33}{flops:>9.1e}{count:>6}{human_time(seconds):>12}{gpu_hours:>11,.0f}{money(gpu_hours * price):>9}")
    
    # Frontier scale: public estimates for the largest models are in the 1e25 to 1e26+ FLOP range.
    print("\nfrontier-scale compute (public estimates for the largest models generally, not for any specific model):")
    for flops in (1e25, 1e26):
        gpu_hours = flops / (989e12 * 0.40) / 3600
        print(f"  {flops:.0e} FLOPs = {gpu_hours / 1e6:.1f}M H100-hours = {money(gpu_hours * 2.50)} at $2.50/h, "
              f"or {gpu_hours / 10000 / 24:.0f} days on 10,000 GPUs")
    print("  (compute only: no failed runs, experiments, data, staff, evaluation or post-training)")
    1. GPUS: peak dense bf16 TFLOP/s and an approximate on-demand rental price per GPU-hour. Prices vary a lot between providers, regions, commitment length and month; check before budgeting.
    2. JOBS: each job's parameters N, tokens D (epochs × dataset tokens for fine-tuning), the operations per parameter per token (4 for LoRA-style training of a frozen model, 6 otherwise), the GPU type and count, and an assumed MFU.
    3. flops = k * n * d and speed = count * peak * 1e12 * mfu: the two formulas above.
    4. gpu_hours = seconds * count / 3600: what you pay for. Eight GPUs for one hour cost as much as one GPU for eight hours.
    5. The last block converts the compute range publicly estimated for the largest recent models (around 10²⁵ to 10²⁶ operations) into GPU-hours and dollars at the same assumptions.
    job                                  FLOPs  GPUs   wall time  GPU-hours     cost
    QLoRA 8B, 3 epochs x 5M tokens     4.8e+17     1   3.2 hours          3    $1.62
    LoRA 8B, 3 epochs x 50M tokens     4.8e+18     1  12.2 hours         12   $18.32
    full fine-tune 8B, 1B tokens       4.8e+19     8   4.2 hours         34   $84.26
    pretrain 1B on 20B tokens          1.2e+20     8  10.5 hours         84  $210.65
    pretrain 8B on 15T tokens          7.2e+23  1024   20.6 days    505,561    $1.3M
    pretrain 70B on 15T tokens         6.3e+24  4096   45.0 days  4,423,660   $11.1M
    
    frontier-scale compute (public estimates for the largest models generally, not for any specific model):
      1e+25 FLOPs = 7.0M H100-hours = $17.6M at $2.50/h, or 29 days on 10,000 GPUs
      1e+26 FLOPs = 70.2M H100-hours = $175.5M at $2.50/h, or 293 days on 10,000 GPUs
      (compute only: no failed runs, experiments, data, staff, evaluation or post-training)

    Look at the cost column from top to bottom: about two dollars, about twenty, about a hundred, about two hundred, about a million, about eleven million, and up to the hundreds of millions for the compute alone of a frontier-scale run. That is a span of eight orders of magnitude. As a sanity check, the 70B row (about 4.4 million H100-hours) is of the same order of magnitude as the several million H100-hours Meta published for its Llama 3 70B model, which was trained on about 15 trillion tokens (real runs also lose time to restarts and lower utilisation).

    Training cost estimatorInteractive

    6 × N × D (or 4 × N × D for LoRA/QLoRA) divided by useful GPU speed. Prices are rough rental figures as of 2026.

    What you can realistically train

    Hardware (as of 2026)Realistic training jobsRough cost
    Laptop CPUthe NumPy models of this course; tiny GPTs like module 5's (66,000 parameters); running small quantised models for inference with Ollamafree
    Free or cheap cloud notebooks (time-limited GPUs)QLoRA of 1B–8B models on small datasets, with interruptionsfree to a few dollars
    One 24 GB consumer GPU (owned or rented)QLoRA up to about 14B; LoRA of 7B–8B; full fine-tuning of models up to about 1B; pretraining toy models of tens of millions of parametersabout $0.30–$1 per hour rented
    One 80 GB data-centre GPU (rented)LoRA of 8B–30B, QLoRA of 70B, faster everythingabout $1.50–$4 per hour
    One 8-GPU server (rented)full fine-tuning of 7B–14B models; pretraining a ~1B model on tens of billions of tokens (a research-grade small model)tens to a few hundred dollars per run
    Frontier clusterspretraining frontier models: thousands to tens of thousands of accelerators for weeks to monthspublic estimates: tens to hundreds of millions of dollars in compute per run

    The bottom row is not available to individuals or small companies, and that is fine: the skills in this course apply directly to the rows above it, and open-weight models give you a strong pretrained starting point for free. For Claude specifically, Anthropic has not published training compute, cluster size, hardware details or cost Not public; the frontier figures here are public estimates for frontier models in general.

    The costs that are not on the GPU bill

    • Experiments. The final run is a fraction of the compute. Learning-rate sweeps, data ablations, ranks, seeds and failed ideas often multiply the total by 2 to 10 for small projects, and frontier labs spend large budgets on small-scale experiments to plan big runs.
    • Failures. Hardware faults, out-of-memory crashes at hour 20, loss spikes. Large runs checkpoint frequently and restart from the last checkpoint; every restart wastes some work.
    • Data. Human-written examples and expert review cost far more than GPU time for most fine-tuning projects. Ten thousand expert-checked examples can cost more than a year of a rented GPU.
    • Evaluation. Generating answers for evaluation sets, LLM-judge calls and human ratings, repeated for every candidate model.
    • Serving. A fine-tuned model has to be hosted (module 11). For many products, inference over the product's lifetime costs more than training ever did.
    • People. Usually the largest cost of all.

    This is why the first question in lesson 10.1 was "do you need to train at all?". An API call to a frontier model costs fractions of a cent to a few cents per request. If prompting plus retrieval gets the quality you need, the comparison with building, evaluating and hosting a fine-tuned model is often lopsided. Fine-tuning pays off when volume is high, latency or privacy requires a self-hosted model, or a small tuned model beats a large prompted one on your evaluation.

    Scaling laws, overtraining, and energy

    Compute-optimal training. Hoffmann et al. (2022, "Training Compute-Optimal Large Language Models", the Chinchilla paper) found that, for a fixed compute budget, loss is lowest when parameters and tokens grow together, at roughly 20 tokens per parameter. A 1B model "should" see about 20B tokens, which is the "pretrain 1B on 20B tokens" row.

    Overtraining on purpose. Recent open models are trained far beyond that ratio (an 8B model on 15T tokens is almost 2,000 tokens per parameter). Training compute is spent once, but a smaller model is cheaper for every one of the billions of requests it serves afterwards, so labs accept a higher training bill for a smaller, better model per parameter Industry practice.

    Why MFU is low. Peak numbers assume large, perfectly shaped matrix multiplications all the time. Real models also do memory-bound work (normalisation, activation functions, attention softmax), GPUs wait on each other for gradients and sharded weights, and pipelines have idle bubbles. FlashAttention and fused kernels exist mostly to raise MFU.

    Energy. A data-centre GPU draws on the order of 700 W under load, and a server adds CPUs, networking and cooling. A million GPU-hours is therefore on the order of a gigawatt-hour of electricity, which is why data-centre power has become a major constraint for frontier training. For a single fine-tuning run on one GPU, the energy is comparable to running a household appliance for a day.

    Common mistakes and debugging tips

    Using peak FLOP/s as real speed

    A plan that assumes 100% utilisation finishes in a third of the real time and budget.

    Fix: assume 25–40% MFU for planning, then measure tokens per second in the first minutes of the real run and recompute.

    Budgeting only the final run

    The final run fits the budget; the ten exploratory runs before it do not.

    Fix: plan explicitly for experiments: start with a small model or a data subset to tune settings cheaply, then scale up once.

    Paying for idle GPUs

    A rented GPU keeps billing while you debug the data loader or sleep after the run finished.

    Fix: debug on a CPU or a cheap small GPU with a tiny model, write scripts that save the adapter and exit, and use instances that stop automatically.

    Key takeaways

    • Training compute ≈ 6 × parameters × tokens (about 4× for LoRA); time = compute ÷ (GPUs × peak × MFU).
    • A QLoRA fine-tune of an 8B model on a small dataset costs a few dollars; pretraining capable models costs millions; frontier runs are publicly estimated at tens to hundreds of millions in compute alone.
    • Experiments, failures, data, evaluation, serving and people often cost more than the final run.
    • Claude's training compute, hardware and cost are not public; open-weight models plus LoRA are the realistic route for everyone else.

    Exercise: budget a real project

    You have 20,000 support conversations averaging 400 tokens each and want to fine-tune an 8B open model for 3 epochs. 1) How many training tokens is that? 2) Estimate time and cost with QLoRA on one RTX 4090-class GPU at 25% MFU, and with LoRA on one H100 at 35% MFU. 3) Add a realistic experiment budget and compare with sending the same 20,000 requests to an API per month at an assumed $0.01 per request.

    Hint

    Tokens = conversations × tokens × epochs. Use 4ND for LoRA. Remember that the training tokens include the masked prompt tokens too: the model still processes them.

    Show a solution

    1) 20,000 × 400 × 3 = 24 million tokens. 2) 4 × 8×10⁹ × 2.4×10⁷ = 7.7×10¹⁷ operations. On the 4090: 7.7×10¹⁷ ÷ (165×10¹² × 0.25) ≈ 18,600 s ≈ 5.2 hours ≈ $2.60. On the H100: ÷ (989×10¹² × 0.35) ≈ 2,200 s ≈ 37 minutes ≈ $1.50. 3) Even with 10 runs for experiments, compute stays around $15–$30. The API comparison is about $200 per month for 20,000 requests. The deciding costs are therefore elsewhere: preparing and checking the data, evaluating, and hosting the fine-tuned model (a GPU serving it around the clock costs far more per month than the training did). Run the numbers for your own volumes; at millions of requests per month a small self-hosted model often wins, at thousands the API usually does.

    Check your understanding

    Roughly how many floating-point operations does it take to train a 1B-parameter model on 20B tokens?

    1. About 1.2 × 10²⁰
    2. About 2 × 10¹⁰
    3. About 6 × 10²⁵
    6 × 10⁹ × 2×10¹⁰ = 1.2×10²⁰. 2×10¹⁰ is just the token count; 6×10²⁵ is in the range estimated for frontier-scale runs.

    A job is estimated at 10 hours assuming 100% of the GPU's peak speed. What is a realistic plan?

    1. 10 hours
    2. 5 hours, because GPUs are faster than their specs
    3. Roughly 25 to 40 hours, because real utilisation is a fraction of peak
    Real training reaches perhaps 25–40% of peak (MFU), so the time is 2.5 to 4 times longer than the ideal. Measure throughput early in the run and update the estimate.

    Which statement about Claude's training cost is accurate?

    1. Anthropic has published its exact training compute and hardware
    2. It is not public; frontier figures in this lesson are public estimates for frontier models in general
    3. It is about the same as a LoRA fine-tune of an 8B model
    Anthropic has not published compute, hardware or cost for training Claude. Public estimates for frontier models in general are in the tens to hundreds of millions of dollars of compute, many orders of magnitude above a LoRA fine-tune.

    Lesson 10.8Module 10: Fine-tuning and training

    Model evaluation and benchmarking

    • ⏱ 20 min read
    • Advanced

    Learning objectives

    • Build an evaluation set that is held out, representative and compared against a trivial and a prompted baseline.
    • Choose and compute metrics: exact match, token F1, lenient matching, multiple-choice accuracy, pass@k, perplexity, and judge-based scores.
    • Put an uncertainty interval around a score and decide whether a difference is real.
    • Know the main public benchmarks, what they measure, and why contamination and saturation limit them.

    Every earlier lesson ended with "measure it". This one is about how. Evaluation is where fine-tuning projects succeed or quietly fail: without a trustworthy evaluation you cannot tell whether your new model is better, whether a change helped, or whether the model forgot something important. Evaluation is also how the field compares frontier models, including Claude, so understanding its limits makes you a better reader of model announcements.

    Analogy: a driving test, not a quiz on the practice route

    A driving examiner does not test you on the exact streets where you practised, does not let you see the route in advance, and checks several things at once: control, rules, judgement in unexpected situations. A single test on one day can be lucky or unlucky, so a narrow pass means less than a clear one. Good model evaluation follows the same rules: unseen questions, several skills, an honest margin of error, and no peeking.

    The foundations: held-out data and baselines

    • Held-out data. Score only on examples the model never trained on, split off before training and decontaminated (lesson 10.2). Measuring on training data rewards memorisation, the warning from lesson 2.6.
    • Representative. The evaluation set should look like real traffic: the same mix of topics, lengths, languages and difficult cases, including the requests the model should refuse or answer with "I don't know".
    • Baselines. Always report a trivial baseline (the most common answer, random choice among options) and the model you started from with a good prompt. A fine-tune that beats nothing, or does not beat its own base model prompted well, is not an improvement.
    • Regression checks. Besides the target task, keep a small set of general questions, safety prompts and format checks to catch forgetting (lesson 10.4).

    Metrics

    MetricUse it forWeakness
    Exact match (after normalising case, punctuation, articles)short factual answers, classification labelsa correct answer in a full sentence counts as wrong
    Token F1short answers where partial overlap means partial creditrewards shared words, not correctness
    Contains / regex extractionanswers expected inside longer text ("the answer is 42")can reward answers that list every option
    Multiple-choice accuracyknowledge and reasoning benchmarksdoes not test writing the answer; chance level is not zero
    pass@k with unit testscode generationonly as good as the tests
    Perplexitycomparing language models on the same text and tokenizer (lesson 1.2)says nothing about helpfulness, truthfulness or following instructions
    LLM-as-judgeopen-ended answers, style, helpfulness, at scalejudge biases (position, length, its own style); must be checked against human ratings
    Human evaluation (ratings or pairwise preference)the final word on qualityslow, expensive, and raters disagree; needs guidelines

    Perplexity, introduced in lesson 1.2, is the exponential of the average negative log-probability per token: a model with perplexity 2.46 on a text is, on average, as unsure as choosing among about 2.5 equally likely tokens. It is excellent for pretraining and for checking that a fine-tune did not damage general language modelling, and nearly useless for deciding whether an assistant is helpful.

    For code, the standard metric is pass@k (Chen et al., 2021, "Evaluating Large Language Models Trained on Code", which introduced HumanEval): the probability that at least one of k generated programs passes the unit tests. Sampling exactly k programs gives a noisy estimate, so the paper generates n ≥ k samples, counts the c that pass, and uses an unbiased formula:

    pass@k=1−(n−ck)(nk)

    In words: the chance that a random group of k samples, picked from the n generated ones, contains no passing program is the number of all-failing groups divided by the number of all groups. One minus that is the chance at least one passes. Average it over all problems.

    Note what pass@k means for a product: pass@10 = 75% is only useful if something (tests, a user) can pick the right one of ten answers. If users see one answer, pass@1 is the number that matters.

    A tiny evaluation harness

    The script scores saved answers of a "base" and a "fine-tuned" model on 12 short questions with three metrics, compares them with a paired bootstrap, computes pass@k, checks the questions for contamination against training documents, and computes a perplexity. Using saved answers makes every run reproducible; in a real project you generate them once per model and store them with the model version.

    # @run
    # eval_harness.py: a tiny but honest evaluation harness.
    # Scores saved model answers with exact match and token F1, compares two models with a paired bootstrap
    # confidence interval, computes pass@k for code problems, and checks the test set for contamination.
    # The "model answers" are fixed strings so the results are reproducible; in practice you generate them once
    # per model with temperature 0 (or several samples for pass@k) and save them to a file.
    import math
    import re
    from collections import Counter
    
    import numpy as np
    
    TEST = [  # (question, list of accepted answers)
        ("What is the capital of Australia?", ["Canberra"]),
        ("How many bits are in a byte?", ["8", "eight"]),
        ("Which planet is known as the Red Planet?", ["Mars"]),
        ("What does HTTP status code 404 mean?", ["Not Found"]),
        ("What is 12 times 12?", ["144"]),
        ("Which data structure is first in, first out?", ["queue", "a queue"]),
        ("What is the chemical symbol for gold?", ["Au"]),
        ("In which year did the first Moon landing take place?", ["1969"]),
        ("What is the default port for HTTPS?", ["443"]),
        ("Which sorting algorithm has an average time of O(n log n) and sorts in place: merge sort or quicksort?", ["quicksort"]),
        ("What is the square root of 81?", ["9", "nine"]),
        ("Which language is used to style web pages?", ["CSS"]),
    ]
    
    ANSWERS = {
        "base model": ["Sydney", "8 bits.", "Mars", "Not found", "144", "A stack", "Au", "1969", "443",
                       "Merge sort", "9", "JavaScript"],
        "fine-tuned": ["Canberra.", "There are 8 bits in a byte.", "Mars", "404 means Not Found.", "144",
                       "A queue", "Au", "1968", "Port 443", "Quicksort", "Nine", "CSS"],
    }
    
    
    def normalise(text):
        """Lowercase, drop punctuation and the articles a/an/the, collapse spaces (the usual SQuAD-style rules)."""
        text = re.sub(r"[^\w\s]", " ", text.lower())
        return " ".join(w for w in text.split() if w not in {"a", "an", "the"})
    
    
    def exact_match(pred, golds):
        return float(any(normalise(pred) == normalise(g) for g in golds))
    
    
    def token_f1(pred, golds):
        best = 0.0
        for g in golds:
            p, t = normalise(pred).split(), normalise(g).split()
            common = sum((Counter(p) & Counter(t)).values())
            if common:
                prec, rec = common / len(p), common / len(t)
                best = max(best, 2 * prec * rec / (prec + rec))
        return best
    
    
    def contains(pred, golds):
        """Lenient: the accepted answer appears as whole words inside the prediction."""
        return float(any(re.search(r"\b" + re.escape(normalise(g)) + r"\b", normalise(pred)) for g in golds))
    
    
    scores = {}
    print(f"{'model':<12}{'exact match':>13}{'token F1':>10}{'contains':>10}")
    for name, preds in ANSWERS.items():
        em = np.array([exact_match(p, g) for p, (_, g) in zip(preds, TEST)])
        f1 = np.array([token_f1(p, g) for p, (_, g) in zip(preds, TEST)])
        ct = np.array([contains(p, g) for p, (_, g) in zip(preds, TEST)])
        scores[name] = ct
        print(f"{name:<12}{em.mean():>13.0%}{f1.mean():>10.2f}{ct.mean():>10.0%}")
    print("(the fine-tuned model answers in full sentences, so strict exact match under-counts it)")
    
    # Paired bootstrap: resample the SAME questions for both models and look at the difference.
    rng = np.random.default_rng(0)
    a, b = scores["fine-tuned"], scores["base model"]
    idx = rng.integers(0, len(TEST), size=(5000, len(TEST)))
    diffs = a[idx].mean(1) - b[idx].mean(1)
    lo, hi = np.percentile(diffs, [2.5, 97.5])
    print(f"\nfine-tuned minus base ('contains'): {a.mean() - b.mean():+.0%}, "
          f"95% bootstrap interval [{lo:+.0%}, {hi:+.0%}] on only {len(TEST)} questions")
    
    
    def pass_at_k(n, c, k):
        """Unbiased pass@k (Chen et al., 2021): chance that at least one of k samples, drawn from n
        generated samples of which c pass the unit tests, is correct."""
        if n - c < k:
            return 1.0
        return 1.0 - math.comb(n - c, k) / math.comb(n, k)
    
    
    passing = [10, 7, 3, 1, 0, 0, 5, 2]          # correct samples out of n = 10, for 8 coding problems
    print("\npass@k over 8 coding problems, 10 samples each:")
    for k in (1, 3, 10):
        print(f"  pass@{k:<2} = {np.mean([pass_at_k(10, c, k) for c in passing]):.3f}")
    
    # Contamination: does any test question appear (as long word n-grams) in the fine-tuning data?
    TRAIN_DOCS = [
        "Quiz night! What is the capital of Australia? Many people say Sydney but the answer is Canberra.",
        "HTTPS uses TLS to encrypt traffic between the browser and the server.",
        "Common interview question: which data structure is first in, first out? Answer: a queue.",
    ]
    
    
    def ngrams(text, n=5):
        w = normalise(text).split()
        return {" ".join(w[i:i + n]) for i in range(len(w) - n + 1)}
    
    
    train_grams = set().union(*(ngrams(d) for d in TRAIN_DOCS))
    flagged = [q for q, _ in TEST if ngrams(q) & train_grams]
    print(f"\ncontamination check (5-gram overlap after normalising): {len(flagged)} of {len(TEST)} test questions found in training data")
    for q in flagged:
        print("  -", q)
    
    clean = [i for i, (q, _) in enumerate(TEST) if q not in flagged]
    for name, sc in scores.items():
        print(f"{name:<12} 'contains' on all {len(TEST)} questions {sc.mean():.0%}, on the {len(clean)} clean ones {sc[clean].mean():.0%}")
    
    # Perplexity from per-token probabilities (what a language model assigned to the reference text).
    probs = np.array([0.42, 0.91, 0.08, 0.66, 0.30, 0.75])
    print(f"\nperplexity of a 6-token reference = exp(mean NLL) = {math.exp(float(-np.log(probs).mean())):.2f}")
    1. TEST: each question with a list of accepted answers ("8" and "eight"). Writing down acceptable variants is part of building a fair test.
    2. ANSWERS: the saved outputs. The fine-tuned model answers in sentences ("There are 8 bits in a byte."), the base model in fragments, and both make some mistakes.
    3. normalise: lowercase, remove punctuation and the articles a/an/the, collapse spaces. These are the usual rules for short-answer question answering.
    4. exact_match, token_f1, contains: strict, partial-credit and lenient scoring. contains uses word boundaries so "8" does not match "18".
    5. The bootstrap block draws 5,000 resamples of the 12 question indices (with replacement), computes the difference between the two models on the same resampled questions, and takes the 2.5th and 97.5th percentiles as a 95% interval.
    6. pass_at_k(n, c, k): the formula above with math.comb, averaged over 8 problems with 10 samples each.
    7. The contamination block builds 5-word n-grams of each question after normalising and looks for them in the training documents.
    8. The last line turns six per-token probabilities into a perplexity.
    model         exact match  token F1  contains
    base model            58%      0.64       67%
    fine-tuned            67%      0.80       92%
    (the fine-tuned model answers in full sentences, so strict exact match under-counts it)
    
    fine-tuned minus base ('contains'): +25%, 95% bootstrap interval [-8%, +58%] on only 12 questions
    
    pass@k over 8 coding problems, 10 samples each:
      pass@1  = 0.350
      pass@3  = 0.556
      pass@10 = 0.750
    
    contamination check (5-gram overlap after normalising): 2 of 12 test questions found in training data
      - What is the capital of Australia?
      - Which data structure is first in, first out?
    base model   'contains' on all 12 questions 67%, on the 10 clean ones 80%
    fine-tuned   'contains' on all 12 questions 92%, on the 10 clean ones 90%
    
    perplexity of a 6-token reference = exp(mean NLL) = 2.46

    Four lessons in one output:

    • The metric changes the story. By exact match the fine-tuned model is 9 points better; by the lenient "contains" it is 25 points better, because strict matching punishes its full-sentence style. Choose the metric that matches what users need, and report it consistently.
    • Small sets are noisy. +25 points sounds decisive, but with 12 questions the 95% interval runs from −8 to +58 points: it includes zero. You would need many more questions to be confident. As a rule of thumb, the standard error of an accuracy p on n questions is p(1−p)/n: about ±4.5 points at p = 0.8 with 80 questions, ±1.3 with 1,000.
    • pass@k grows quickly with k: 0.35 for one try, 0.75 for ten.
    • Contamination inflates scores. Two test questions appear in the training documents. On the 10 clean questions, the fine-tuned model's lead shrinks from 25 to 10 points: part of its apparent gain was memorisation.
    Metric playground and pass@kInteractive

    Type a model answer and the accepted answers (separated by |). The scores use the same rules as eval_harness.py.

    Public benchmarks

    Public benchmarks let different models be compared on the same questions. A few that you will see in model announcements, including the system cards Anthropic publishes for Claude models Public:

    BenchmarkMeasuresFormat
    MMLU (Hendrycks et al., 2020)knowledge across 57 subjectsmultiple choice, 4 options
    GPQA (Rein et al., 2023)hard graduate-level science questions written to resist web searchmultiple choice
    GSM8K (Cobbe et al., 2021)grade-school maths word problemsfinal numeric answer
    HumanEval (Chen et al., 2021)writing short Python functionspass@k with unit tests
    SWE-bench (Jimenez et al., 2023)fixing real GitHub issues in real repositoriesthe repository's tests must pass
    TruthfulQA (Lin et al., 2021)avoiding common misconceptionsgeneration or multiple choice

    Three limits apply to all of them. Saturation: once top models score near the maximum (GSM8K, HumanEval and MMLU are close to this for frontier models), the benchmark no longer separates them, and new, harder ones replace it. Contamination: popular benchmark questions leak into web data and training sets, inflating scores in ways that are hard to detect from outside. Setup sensitivity: prompt format, number of examples in the prompt, answer extraction and sampling settings can move scores by several points, so numbers from different reports are often not comparable. For your own fine-tune, public benchmarks are mainly a forgetting check; the evaluation that matters is the one built from your task.

    Open tools run many benchmarks with standard settings, for example EleutherAI's lm-evaluation-harness. A typical command looks like this (it needs the package and a GPU; not executed by our tests, and option names can change between versions):

    pip install lm-eval
    lm_eval --model hf --model_args pretrained=Qwen/Qwen2.5-1.5B-Instruct,peft=./adapter-best \
            --tasks gsm8k,mmlu --batch_size 8

    Judging open-ended answers

    Most assistant answers have no single correct string. Two scalable options are rubric checks (does the answer include the required step, the right link, the refusal?) written as code where possible, and LLM-as-judge: a strong model scores answers against a rubric or picks the better of two. Judges are useful but biased: they tend to prefer the first answer shown, longer answers, and answers in their own style. Counter-measures are to swap the order and average, to ask for a short justification before the verdict, to use a different model family as judge than the one being tested, and to check agreement with human ratings on a sample of 50 to 100 items before trusting the judge on thousands. Hallucination checks (lesson 5.9) fit here too: for retrieval answers, ask the judge whether each claim is supported by the provided sources.

    Statistics for model comparisons

    Paired comparisons. When two models answer the same questions, compare them per question (paired), as the bootstrap in the script does. Many questions are easy for both or hard for both; pairing removes that shared variation and gives much tighter intervals than comparing two independent accuracies.

    Several sources of noise. The question sample is one source; others are sampling temperature (generate several answers per question, or use temperature 0 where the API allows it), the prompt wording (evaluate with two or three paraphrased prompts), and the training seed (train twice). A difference smaller than the spread across seeds is not a result.

    Multiple comparisons. If you try 20 variants and keep the best on the validation set, its score is optimistic: some of the gain is luck. Choose with the validation set, then report once on a test set you did not use for choices.

    Pairwise preferences and Elo-style ratings. Public arenas collect many human votes between two anonymous models and fit a rating model (Bradley–Terry, the same model behind the reward models of lesson 6.4). Ratings reflect the voting population and the kinds of prompts they send, and style influences votes, so they complement rather than replace task-specific evaluation.

    Common mistakes and debugging tips

    A tiny evaluation set and a confident conclusion

    Twenty questions, one point of difference, and a decision to ship. The interval would have included zero, or even a loss.

    Fix: use hundreds of items where possible, compute a bootstrap interval for the paired difference, and say "no significant difference" when the interval includes zero.

    A metric that measures the format, not the answer

    Exact match marks "Canberra." correct only after normalisation and "The capital is Canberra" wrong; a model fine-tuned to answer in sentences looks worse while being better.

    Fix: extract the answer (or use contains/regex rules) and read 20 scored examples by hand to confirm the metric agrees with your judgement.

    Evaluating only the target task

    The fine-tune is better on support questions and quietly worse at everything else, including refusing harmful requests.

    Fix: keep a regression suite: general questions, safety prompts, multi-turn and format checks, run on every candidate model alongside the target set.

    Tuning on the test set

    Every change is checked against the test set and kept if the score goes up. After 30 rounds the test score is inflated by selection.

    Fix: make decisions with a validation set; open the test set once at the end, and refresh it periodically with new examples.

    Key takeaways

    • Evaluate on held-out, decontaminated, representative data, against a trivial and a prompted baseline, with regression checks for forgetting.
    • Pick metrics that match the product: exact match, F1, lenient matching, pass@k, judges, humans; perplexity measures language modelling, not helpfulness.
    • Put an interval around every comparison; small evaluation sets cannot separate close models.
    • Public benchmarks saturate, leak into training data and depend on setup; your own task evaluation is what decides.

    Exercise: make the comparison trustworthy

    1) Add a trivial baseline to eval_harness.py: a "model" that answers every question with the most common gold answer form in the test set (for example "9"). 2) Add 20 more questions with answers for both models (invent plausible answers, including mistakes) and rerun the bootstrap. Does the interval for the difference still include zero? 3) Swap the order in which the bootstrap compares the models and confirm the interval just flips sign.

    Hint

    A trivial baseline is just another entry in ANSWERS: a list with the same constant string 12 (or 32) times. The bootstrap interval width shrinks roughly with the square root of the number of questions.

    Show a solution
    ANSWERS["constant"] = ["9"] * len(TEST)          # trivial baseline
    # ... after adding 20 (question, answers) pairs to TEST and 20 answers to each model ...
    for name, preds in ANSWERS.items():
        assert len(preds) == len(TEST), name             # catches misaligned lists early
    # swap check:
    d2 = b[idx].mean(1) - a[idx].mean(1)
    print(np.percentile(d2, [2.5, 97.5]))                # equals minus the earlier interval, reversed

    The constant baseline scores 1 in 12 (8%) on the original set, the chance level for this test. With 32 questions and a similar gap, the interval is roughly 40% narrower (the square root of 32/12 is about 1.6) and will usually exclude zero if the gap stays around 20 points. The assert matters: a missing answer shifts every following answer by one question, a bug that silently ruins the evaluation.

    Mini-project: fine-tune and evaluate a small support assistant

    Take an open-weight instruct model and make it a better support assistant for a product of your choice (a real app, an open-source project, a fictional company), then prove, with numbers and honest intervals, whether it worked and what it cost. All the pieces exist in this module; the project is about connecting them with discipline.

    1. Decide. Write one paragraph using lesson 10.1: what behaviour should change, why prompting and retrieval are not enough (or test that they are), and which licence your base model has.
    2. Evaluation first. Write 100 to 200 test questions with accepted answers or rubric points, including 15% that should be refused or answered with "I don't know". Score the base model with a good system prompt (your baseline) and a trivial baseline.
    3. Data. Collect or write 500 to 2,000 conversations. Clean them with clean_data.py's steps (add your own filters), decontaminate against the test set, and validate and split with instruction_dataset.py (stratified by category, exercise 10.3).
    4. Budget. Estimate memory with vram_estimator.py and cost with cost_calculator.py for your model size; choose a GPU (lesson 10.7). Keep the total, including experiments, under a limit you set in advance.
    5. Train. Run qlora_train.py (or a trainer you prefer) with rank 16, 2 to 3 epochs and early stopping on validation loss. Then one change at a time: learning rate, rank, or 20% general replay data.
    6. Evaluate. Score every candidate on the test set with the harness (exact/contains plus an LLM judge with swapped order for open answers), compute paired bootstrap intervals against the baseline, and run a 30-question regression set of general and safety prompts.
    7. Report. One page: the table of scores with intervals, cost in GPU-hours and dollars, five example answers before and after, what the model got worse at, and a recommendation (ship, keep prompting, or collect more data).
    Hints / reference solution

    Model size. Start with a 1B to 3B instruct model: runs take minutes, mistakes are cheap, and the workflow is identical for 8B. Move up only when the small model's ceiling is clearly the limit.

    Saving generations. Write each model's test answers to answers-<model>-<date>.jsonl with the question id, the model id and adapter path, the generation settings and the answer. The harness then reads files instead of the ANSWERS dict, and every number in your report can be reproduced without a GPU.

    Judge prompt. Give the judge the question, the reference points and the answer; ask for a one-sentence reason and then a score from 1 to 5. For pairwise comparisons, run both orders and count a win only if both agree.

    What to expect. Typical outcomes: the fine-tuned model follows the format and tone far more consistently, refuses out-of-scope requests better when the data showed how, improves little on facts it was never given (use retrieval for those, module 8), and loses a few points on unrelated general questions unless replay data was mixed in. A prompted baseline is often closer than people expect; a result of "no significant difference" is a valid and useful finding.

    Stretch goals. Add DPO on 300 preference pairs on top of the SFT adapter (lesson 10.5); quantise the merged model and serve it with Ollama (module 11); compare the same evaluation through the Claude API with a strong system prompt and retrieval.

    Check your understanding

    A fine-tuned model scores 25 points higher than the base model on 12 questions, with a 95% bootstrap interval of −8 to +58 points. What should you conclude?

    1. The fine-tune is clearly better
    2. The evidence is too weak: the interval includes zero, so more questions are needed
    3. The fine-tune is worse
    An interval that includes zero means the data are consistent with no difference (or even a small loss). The point estimate is promising, but 12 questions cannot separate the models; more test items narrow the interval.

    A model generates 10 programs per problem, and on one problem 3 pass the tests. What is pass@1 for that problem?

    1. 1.0, because at least one passed
    2. 0.03
    3. 0.3
    With k = 1 the formula reduces to c / n = 3 / 10: the chance that a single randomly chosen sample passes. "At least one of ten passed" is pass@10.

    Why is perplexity not enough to evaluate a chat assistant?

    1. It measures how well the model predicts reference text, not whether its answers are helpful, correct or appropriately cautious
    2. Because it can only be computed for code
    3. Because lower perplexity always means a worse assistant
    Perplexity is a language-modelling measure on a fixed text and tokenizer. An assistant can predict text well and still answer unhelpfully or invent facts; task metrics, judges and human evaluation measure those.