02.6 How LLMs Are Trained

Understand LLMsLesson 6 of 1020,447 words14 parts
Module 02 · 0 of 9 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10

Every behaviour you see from an LLM, good or bad, was put there by training: its knowledge and its knowledge cutoff, its helpful tone and its occasional flattery, its willingness to follow a system prompt, its refusals, its reasoning, and its habit of saying "Great question!". This lesson follows a model from raw web text to a released product, stage by stage, so that you can recognize where each behaviour comes from and design your applications around it.

What you'll learn

  • The full training pipeline, from data collection through pretraining, mid-training and post-training to safety evaluation and release
  • Where pretraining data comes from, how it's cleaned, filtered and deduplicated, how much of it there is, and the copyright debates around it
  • The pretraining objective (next-token prediction with cross-entropy), how to measure it with perplexity, and what it costs in compute
  • Scaling laws (Kaplan, Chinchilla), why today's small models are "over-trained", and the debate about emergent abilities
  • What a base model is, and how it differs from the instruct model you call through an API, with a runnable side-by-side demo
  • Post-training: supervised fine-tuning, chat templates, RLHF, DPO, Constitutional AI, reinforcement learning with verifiable rewards, and tool-use training
  • Safety training, red-teaming, pre-release evaluations, and how to read a model card or system card
  • Distillation and synthetic data, and what licence terms say about training on model outputs
  • Side effects of training you'll notice at work: sycophancy, verbosity, over-refusal, style quirks, knowledge cutoffs
  • Why behaviour changes between model versions, and why you pin versions and re-run evals
  • The vocabulary of fine-tuning (continued pretraining, SFT, preference tuning, LoRA, QLoRA) and when each term applies, as a preview of Module 13A
  • At a glance: mixed precision, distributed training, learning-rate schedules, data contamination and model collapse

What you don't need

  • Any experience training models. You won't train an LLM in this path, and this lesson doesn't teach fine-tuning how-to (that decision belongs to Module 13A).
  • Maths beyond arithmetic. Every formula is explained in words.
  • A GPU. Every local demo runs on a laptop CPU.

Setup

The local demos need Python 3.11+, PyTorch and Hugging Face Transformers. The first run downloads gpt2 (about 550 MB) and the two Qwen2.5-0.5B models (about 1 GB each):

bash
uv add torch transformers        # or: pip install torch transformers

First time? Create a project with uv init llm-basics && cd llm-basics, then run scripts with uv run python file.py. The outputs in this lesson were produced with PyTorch 2.15.0 and Transformers 5.22.1. Transformers 5.x is a recent major version, so a newer major release may rename things again; if a sample fails after an upgrade, check its changelog.

Some demos (data cleaning, scaling arithmetic, reward functions, DPO loss) use only the Python standard library.

No API keys are needed for this lesson. Provider APIs appear only in passing, and are covered properly in Module 03.


What you must be able to do after this lesson#

  • Describe the stages of training an LLM from pretraining to release
  • Explain what a base model is and how it differs from a chat model
  • Explain what supervised fine-tuning and preference tuning do
  • Explain what reinforcement learning with verifiable rewards adds
  • Explain how training side effects show up in your app
  • Explain how model versions change over time

Why this matters for an AI engineer#

You won't train frontier models, but you'll work with their consequences every day:

You'll hear... You'll understand it after...
"It's trained on 15 trillion tokens." 2.5 How much data?
"The training data was filtered with a quality classifier." 2.2 From raw crawl to training data
"Are they allowed to train on that? What about copyright?" 2.7 Copyright, licensing and consent
"This model has lower perplexity on our domain." 3.2 Perplexity
"It's Chinchilla-optimal." / "That 8B model is heavily over-trained." Part 4: Scaling laws
"Download the base model, not the instruct one." Part 5: The base model
"The model ignores our system prompt when the user pushes back." 6.3 System prompts are a trained behaviour
"It was aligned with RLHF." / "We used DPO." Part 7: Preference tuning
"Reasoning models were trained with RL on verifiable rewards." Part 8
"Check the system card before we adopt it." 9.4 Model cards and system cards
"Can we train our model on GPT outputs?" 10.4 Licence terms
"Why does it agree with everything the user says?" 11.1 Sycophancy
"The model was released in September but its knowledge stops in June." 11.5 Knowledge cutoff vs release date
"The provider updated the model and our outputs changed." Part 12: Model versions and lifecycle

Part 1: The big picture#

1.1 From raw text to assistant: the pipeline#

Modern LLMs are built in stages. Each stage starts from the previous stage's model and changes it with a different kind of data and a different training signal:

flowchart TB
    data["1. Data<br/>collect, clean, filter, deduplicate, mix<br/>(trillions of tokens)"] --> pre["2. Pretraining<br/>next-token prediction on the data mix<br/>(weeks to months, thousands of GPUs)"]
    pre --> mid["3. Mid-training<br/>annealing on top-quality data,<br/>long-context extension"]
    mid --> base(["Base model<br/>a document completer"])
    base --> sft["4. Supervised fine-tuning (SFT)<br/>example conversations"]
    sft --> pref["5. Preference tuning<br/>RLHF, DPO, RLAIF"]
    pref --> rl["6. Reinforcement learning<br/>verifiable rewards: maths, code, tools, agents"]
    rl --> safety["7. Safety evaluation<br/>red-teaming, dangerous-capability tests,<br/>system card"]
    safety --> release(["8. Release<br/>API snapshot, open weights, chat product"])
    safety -. "problems found" .-> sft
  • Pretraining (stages 1–3) produces a base model: a network that has absorbed language, facts and skills from trillions of tokens of text, but that only knows how to continue documents.
  • Post-training (stages 4–6) turns the base model into an assistant that follows instructions, holds a conversation, refuses harmful requests, reasons step by step and uses tools. "Post-training" is the umbrella term; you'll also hear alignment, fine-tuning and instruction tuning used loosely for parts of it.
  • Safety evaluation and release (stages 7–8) decide whether and how the model ships.

1.2 An analogy: educating a model#

Stage Analogy What the model gains
Pretraining Reading an enormous library, cover to cover, trying to guess each next word Language, world knowledge, coding ability, reasoning patterns, every writing style
Mid-training A focused revision course on the best textbooks, plus practice reading very long documents Sharper skills in maths, code and reasoning; a longer usable context
SFT An apprenticeship: watching thousands of worked examples of a good assistant at work The format of being an assistant: answering, following instructions, taking turns
Preference tuning A coach who watches you answer and says "this one was better than that one" Taste: helpfulness, tone, honesty, harmlessness, as judged by people (or by AI against written principles)
RL with verifiable rewards Practice exams with an answer key, thousands of times over Reliable maths, coding and multi-step reasoning; using tools to finish tasks
Safety evaluation A licensing exam and a background check before starting the job Evidence about risks, written up in a system card

1.3 How the stages compare#

Pretraining Mid-training SFT Preference tuning RL (verifiable rewards)
Data Raw text and code Curated high-quality and long documents Example conversations (prompt → ideal answer) Pairs of answers with a "better" label Tasks with automatically checkable answers (plus judge-graded tasks)
Typical scale Trillions of tokens Hundreds of billions of tokens Thousands to millions of examples Tens of thousands to millions of comparisons Thousands to millions of tasks, many attempts each
Training signal Cross-entropy on the next token Same Cross-entropy on the assistant's tokens only Reward model + RL, or a direct preference loss Reward from a program (tests pass? answer correct?)
Compute share The vast majority Small Small Small Historically small, now growing fast
What it changes What the model knows and can do Specific skills, context length How it behaves and formats answers What it prefers to say How well it reasons and completes tasks

Part 2: Pretraining data#

Deep-dive

"You are what you eat" applies to LLMs more literally than to anything else in software. A model can only know what was in its data, it reproduces the styles and biases of its data, and the single biggest lever on its quality, after scale, is how carefully the data was chosen.

2.1 Where the data comes from#

Source Examples What it contributes
Web crawls Common Crawl, a non-profit that has crawled the public web since 2008; each crawl captures a few billion pages, and the archive is measured in petabytes. Companies also run their own crawlers. Breadth: every topic, style and language. Also most of the junk.
Code Public repositories (for example GitHub), Q&A sites, documentation Programming ability. Code also seems to help structured reasoning more generally.
Books Public-domain books, licensed collections, and (controversially) pirated "shadow library" collections Long-form, coherent, edited writing; long-range structure
Academic papers arXiv, open-access journals, patents Scientific and mathematical knowledge
Reference works Wikipedia, encyclopaedias, dictionaries Dense, mostly accurate facts
Conversations and forums Q&A sites, discussion forums Question-answer patterns, informal language
Multilingual data Web text in other languages, translated text Ability in non-English languages, usually a minority of the mix
Licensed data Deals with publishers, news organizations, stock-media and forum sites High-quality, legally safer content
Synthetic data Text generated by other models: rewritten web pages, generated textbooks, maths problems, code exercises Targeted skills and formats, more data in areas where real data is scarce (Part 10)

Most providers of closed models describe their sources only in general terms ("publicly available data, licensed data, data from users who opted in, synthetic data"). Open-model reports (Llama, Qwen, DeepSeek, OLMo) and open datasets (FineWeb, Dolma, RedPajama, The Pile) give far more detail, and they're where most public knowledge about data pipelines comes from.

2.2 From raw crawl to training data#

Raw web data is mostly unusable: navigation menus, cookie banners, spam, machine-generated pages, near-identical copies, adult content, and personal data. A typical cleaning pipeline throws away the large majority of what was crawled:

flowchart LR
    src["Raw sources<br/>web crawls, code, books,<br/>papers, multilingual,<br/>synthetic data"] --> ext["Extract text<br/>strip HTML, menus, ads"]
    ext --> lang["Language ID"]
    lang --> heur["Heuristic filters<br/>length, symbols,<br/>repetition"]
    heur --> dedup["Deduplicate<br/>exact and near-duplicate"]
    dedup --> qual["Quality classifier<br/>'is this educational,<br/>well-written?'"]
    qual --> safe["PII and toxicity<br/>filtering"]
    safe --> mix["Data mixture<br/>% web, code, maths,<br/>languages..."]
    mix --> tok["Tokenize<br/>trillions of tokens"]
Step What it does Why
Text extraction Pull the main text out of HTML, dropping boilerplate A page's menus and footers aren't useful language
Language identification A small classifier labels each document's language To control how much of each language goes into the mix
URL and domain filtering Block lists of adult, spam, malware and other unwanted domains; some pipelines also remove domains with lots of personal data Cheap first pass
Heuristic quality filters Rules such as: minimum length, ratio of symbols to words, too many repeated lines, too few sentences ending in punctuation, "lorem ipsum" Removes obvious junk cheaply. Rules like these come from published pipelines such as C4, Gopher and FineWeb.
Deduplication Remove exact copies (by hashing) and near-duplicates (documents that are, say, 80% identical), usually with a technique called MinHash The web is full of copies. Duplicates waste compute, and text seen many times is far more likely to be memorized and regurgitated word for word. Research has found that deduplicating makes models better, not just cheaper.
Model-based quality filtering A quality classifier scores each document, and low scorers are dropped or down-weighted Rules can't judge whether text is informative. A classifier can approximate it.
PII filtering Detect and remove or mask personal data such as emails, phone numbers and addresses Privacy and legal compliance; reduces the chance of the model reproducing someone's personal data
Toxicity and safety filtering Classifiers or word lists remove hateful, sexual or otherwise harmful content Less harmful output. But filter too aggressively and the model understands less about these topics, which can hurt its ability to recognize and moderate them.
Decontamination Remove documents containing benchmark test questions So benchmark scores measure ability, not memorization (14.5)

Two published examples show how much effort this involves:

  • Llama 3 (Meta, 2024) used URL-level, document-level (MinHash) and line-level deduplication; heuristic filters; removal of domains with large amounts of personal data; and quality classifiers. Meta trained those classifiers using labels produced by Llama 2, so the previous model generation helped choose the next generation's data.
  • FineWeb (Hugging Face, 2024), an open 15-trillion-token dataset built from 96 Common Crawl snapshots, published every step and ablation. Its FineWeb-Edu subset (1.3T tokens) keeps only pages that a classifier rates as educational. The classifier was trained on scores that Llama-3-70B-Instruct gave to several hundred thousand pages. Small models trained on FineWeb-Edu scored markedly higher on knowledge and reasoning benchmarks than models trained on the same amount of unfiltered FineWeb.

2.3 Try it: a miniature cleaning pipeline#

Here's a toy version of the main steps: exact deduplication by hashing, heuristic quality filters, near-duplicate detection by comparing overlapping word sequences, and PII scrubbing.

python
import hashlib
import re

docs = [
    "Python lists are ordered, mutable collections. Use append() to add an item.",
    "Python lists are ordered, mutable collections. Use append() to add an item.",   # exact copy
    "Python lists are ordered and mutable collections. Use append() to add items!",  # near-copy
    "BUY CHEAP WATCHES!!! BEST PRICE!!! CLICK HERE!!! BUY NOW!!! CHEAP CHEAP CHEAP",
    "Home | About | Contact | Login | Sign up | Privacy | Terms | Cookies | Help",
    "Contact me at jane.doe@example.com or call 555-0142 for the full report.",
    "Photosynthesis converts light energy into chemical energy stored in glucose.",
]

def words(text):
    return re.findall(r"[a-z0-9']+", text.lower())

# --- 1. Heuristic quality filters (simplified versions of rules used in C4, Gopher, FineWeb) ---
def quality_problems(text):
    w = words(text)
    problems = []
    if len(w) < 8:
        problems.append("too short")
    if sum(c.isupper() for c in text) / max(1, sum(c.isalpha() for c in text)) > 0.5:
        problems.append("mostly capitals")
    if text.count("!") > 3:
        problems.append("too many '!'")
    if text.count("|") > 3:
        problems.append("looks like navigation menu")
    if len(set(w)) / max(1, len(w)) < 0.6:
        problems.append("repetitive")
    return problems

# --- 2. PII scrubbing: replace emails and phone numbers with placeholders ---
def scrub_pii(text):
    text = re.sub(r"[\w.+-]+@[\w-]+\.[\w.]+", "<EMAIL>", text)
    return re.sub(r"\b\d{3}-\d{4}\b", "<PHONE>", text)

# --- 3. Near-duplicate detection: compare sets of overlapping 3-word "shingles" ---
def shingles(text, n=3):
    w = words(text)
    return {" ".join(w[i:i + n]) for i in range(len(w) - n + 1)}

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

kept, seen_hashes = [], set()
for i, doc in enumerate(docs):
    digest = hashlib.sha256(doc.encode()).hexdigest()
    if digest in seen_hashes:
        print(f"doc {i}: DROP  exact duplicate")
        continue
    seen_hashes.add(digest)
    if problems := quality_problems(doc):
        print(f"doc {i}: DROP  low quality ({', '.join(problems)})")
        continue
    similar = [(j, jaccard(shingles(doc), shingles(docs[j]))) for j in kept]
    if similar and max(s for _, s in similar) > 0.3:
        j, s = max(similar, key=lambda x: x[1])
        print(f"doc {i}: DROP  near-duplicate of doc {j} (similarity {s:.2f})")
        continue
    kept.append(i)
    print(f"doc {i}: KEEP  {scrub_pii(doc)}")
Output7 lines
doc 0: KEEP  Python lists are ordered, mutable collections. Use append() to add an item.
doc 1: DROP  exact duplicate
doc 2: DROP  near-duplicate of doc 0 (similarity 0.43)
doc 3: DROP  low quality (mostly capitals, too many '!')
doc 4: DROP  low quality (looks like navigation menu)
doc 5: KEEP  Contact me at <EMAIL> or call <PHONE> for the full report.
doc 6: KEEP  Photosynthesis converts light energy into chemical energy stored in glucose.
  • Exact duplicates are caught cheaply by hashing: identical text gives an identical hash.
  • Near-duplicates need a similarity measure. The Jaccard similarity used here is "shared 3-word chunks divided by all distinct 3-word chunks". Doc 2 differs by a few words, so it shares 43% of its chunks with doc 0. Comparing every pair is impossible across billions of documents, so real pipelines use MinHash with locality-sensitive hashing, a trick that finds likely-similar pairs without comparing everything to everything.
  • Heuristic filters caught the spam and the navigation menu. Real pipelines use dozens of such rules, each tuned by training small models on filtered and unfiltered data and comparing results.
  • PII scrubbing replaced the email and phone number. Real PII detection is much harder: names, addresses and IDs come in endless formats.

2.4 Data mixtures#

After cleaning, data teams decide how much of each kind of data goes into training. This data mixture is one of the most closely guarded and carefully tuned parts of a recipe.

Meta published Llama 3's final pretraining mix in rough terms:

Category Share of tokens
General knowledge ~50%
Mathematics and reasoning ~25%
Code ~17%
Multilingual ~8%

Mixtures are usually chosen by training many small models on different mixes and seeing which do best, then extrapolating to the big run. Some high-quality sources (Wikipedia, textbooks) are upsampled, meaning repeated or weighted more heavily than their natural share, while low-quality web text is downsampled.

What this means for you: a model's strengths and weaknesses follow its mixture. A model trained on 8% multilingual data will usually be noticeably weaker in Tamil or Swahili than in English, and Meta said so explicitly about Llama 3. Always test a model in the languages and domains your users need rather than assuming English benchmark scores carry over (Module 10A).

2.5 How much data?#

Pretraining datasets have grown dramatically:

Model Year Pretraining tokens (published)
GPT-3 2020 ~300 billion
Chinchilla 2022 1.4 trillion
Llama 2 2023 2 trillion
Llama 3 / 3.1 2024 15T+ ("over 15T"; 15.6T for the 405B model)
DeepSeek-V3 2024 14B.7 trillion
Qwen2.5 2024 18 trillion

For scale: 15 trillion tokens is roughly 11 trillion English words. A fast human reader managing 300 words a minute, eight hours a day, would need on the order of 200,000 years to read it.

Most closed-model providers don't publish their token counts. Treat numbers you see for GPT, Claude or Gemini models as rumours unless they come from the provider.

2.6 Why quality matters as much as size#

Early scaling work treated data as interchangeable tokens. Since then, results have repeatedly shown that better data beats more data:

  • Filtering pays. Small models trained on FineWeb-Edu beat models trained on the same number of tokens of less-filtered web text on knowledge and reasoning benchmarks.
  • Deduplication pays. Removing duplicates reduces memorization and improves models at the same compute.
  • Textbook-quality data pays. Microsoft's Phi series ("Textbooks Are All You Need", 2023) showed that small models trained on carefully curated and synthetic "textbook-like" data could match much larger models on some coding and reasoning benchmarks.
  • Late-stage quality pays. Training on the highest-quality data at the end of pretraining (3.6) gives an outsized boost.

The general lesson ("garbage in, garbage out") is one you'll apply directly: the quality of the documents you feed into RAG (Module 05, Module 07) matters as much as the model you choose.

Training data raises legal and ethical questions that are still being settled. As an engineer you don't need to be a lawyer, but you should know the shape of the debate, because it affects which models your company may be willing to use.

The core questions:

  • Is training on copyrighted work "fair use" (US) or covered by text-and-data-mining exceptions (EU, UK, Japan and others)? Supporters argue training extracts patterns rather than copying works, much as a person learns by reading. Critics argue it builds commercial products from creators' work without permission or payment, and that models can reproduce protected text.
  • Does it matter how the data was obtained? Downloading pirated books is a different question from reading public web pages.
  • What about outputs? Separate from training, a model that reproduces copyrighted text or images verbatim creates its own legal risk.
  • Consent and opt-out: should creators be able to refuse? Many sites now block AI crawlers in robots.txt.

Some landmarks (as of November 2026):

Case or rule What happened
Bartz v. Anthropic (US) In June 2025 a federal judge ruled that training Claude on lawfully acquired books was fair use, but that acquiring and keeping pirated copies in a central library was not protected. Anthropic then agreed a $1.5 billion class settlement with authors (case 24-cv-05417, Northern District of California), which the court finally approved on 20 July 2026 (Judge Araceli Martínez-Olguín, who took over the case). Anthropic did not admit liability. According to Class Counsel's status report of 2 September 2026 (docket 688), no class member or objector filed a timely appeal; two notices of appeal came from law firms excluded from the fee award (Edelson P.C. with Oppenheim + Zebrak, and Cowan DeBaets Abrahams & Sheppard), and because both concern only the fee award the parties agree the settlement's Effective Date has passed. The report expected payments to class members to start by early November and no later than 15 November 2026, with a final $450 million instalment from Anthropic still due later. Check the docket for case 24-cv-05417 on CourtListener for the current status.
The New York Times v. OpenAI and Microsoft (US) Filed December 2023, alleging unlicensed use of Times articles for training and verbatim reproduction. Now part of consolidated proceedings in New York and still in pre-trial litigation as of November 2026.
EU AI Act Since 2 August 2025, providers of general-purpose AI models placed on the EU market must publish a "sufficiently detailed" public summary of their training content (using a European Commission template) and have a policy for complying with EU copyright law, including rights-holders' opt-outs.
Licensing deals Many providers have signed content-licensing agreements with publishers, news organizations and platforms, partly to secure data and partly to reduce legal risk.

Courts in different countries are reaching different conclusions, and the outcomes are still moving. Check current status before relying on any of this.

Crawler opt-outs. The major providers publish the names of their training crawlers so site owners can block them in robots.txt:

Provider Training crawler / control token Notes
OpenAI GPTBot Separate from OAI-SearchBot (search) and ChatGPT-User (fetching pages for a user)
Anthropic ClaudeBot Separate from Claude-SearchBot and Claude-User
Apple Applebot-Extended A control token, not a separate crawler. It opts content out of training Apple's foundation models; Applebot still crawls for search.
Common Crawl CCBot Not a model provider, but its archive feeds most open datasets (FineWeb, Dolma, RedPajama) and many labs' pipelines. Blocking it also removes your site from Common Crawl's non-AI uses (research, archiving).
Google Google-Extended A control token, not a separate crawler. It controls use for Gemini training without affecting Google Search.
text
# robots.txt: opt out of AI training crawlers while staying in search results
User-agent: GPTBot
Disallow: /

User-agent: ClaudeBot
Disallow: /

User-agent: Google-Extended
Disallow: /

User-agent: Applebot-Extended
Disallow: /

User-agent: CCBot
Disallow: /

There is no single "no AI" switch: each company publishes its own token, so check each provider's crawler documentation, and expect the list to grow. robots.txt is a convention that well-behaved crawlers honour, not an access control, and it only affects future crawling, not data already collected.

What this means for you:

  • Your company's legal team may restrict which models you use, prefer providers that offer copyright indemnity to enterprise customers, or require models with documented training data. Know where to find this information: model cards, providers' commercial terms, and EU training-data summaries.
  • Output risk is yours too. If your product could reproduce copyrighted material (lyrics, book passages, code under restrictive licences), add guardrails (Module 12).
  • If you publish content, decide deliberately whether you want AI crawlers to use it, and set robots.txt accordingly.
  • Customer data you send to an API is governed by the provider's data-usage terms and your account settings, not by these crawler rules. Check whether it can be used for training (lesson 01, 7.2).

Part 3: Pretraining#

Deep-dive

3.1 The objective: predict the next token#

Pretraining has one objective: at every position in the training text, predict the next token. The loss is the cross-entropy (explained in lesson 01, section 5.1, an optional lesson): the negative logarithm of the probability the model gave to the token that actually came next. Lower is better.

This is self-supervised learning (lesson 01, 1.2): nobody labels anything. Each document provides one training example per token, and a transformer computes predictions for every position of a document in parallel, which is what makes training on trillions of tokens feasible (lesson 04).

Let's look at the losses for a real sentence, using GPT-2 (a small 2019 base model):

python
import math
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

tok = AutoTokenizer.from_pretrained("gpt2")
model = AutoModelForCausalLM.from_pretrained("gpt2")
model.eval()

text = "The capital of France is Paris."
ids = tok(text, return_tensors="pt").input_ids
with torch.no_grad():
    logits = model(ids).logits                 # one score per vocabulary token, at every position
probs = torch.softmax(logits, dim=-1)

print(f"{'context so far':<32} {'actual next':<10} {'P(actual)':>9} {'loss':>6}")
for i in range(ids.shape[1] - 1):
    context = tok.decode(ids[0, : i + 1])
    actual = ids[0, i + 1]
    p = probs[0, i, actual].item()             # probability the model gave the real next token
    print(f"{context!r:<32} {tok.decode(actual)!r:<10} {p:9.3f} {-math.log(p):6.2f}")
Output7 lines
context so far                   actual next P(actual)   loss
'The'                            ' capital'     0.000   9.07
'The capital'                    ' of'          0.164   1.81
'The capital of'                 ' France'      0.007   5.03
'The capital of France'          ' is'          0.122   2.11
'The capital of France is'       ' Paris'       0.032   3.43
'The capital of France is Paris' '.'            0.261   1.34

Read it row by row:

  • After just "The", the model had no reason to expect " capital" out of tens of thousands of possible next tokens. It gave it about a 0.01% chance (shown as 0.000), so the loss is high: 9.07.
  • After "The capital", " of" is a natural continuation: 16% probability, low loss.
  • " Paris" after "The capital of France is" got only 3.2%. GPT-2 is small and old, and many continuations are plausible (" a", " the", " located"...). A modern frontier model would put far more probability on " Paris".

During pretraining, the model computes these losses for every token in a batch of millions of tokens, averages them, and backpropagation nudges every weight to make the actual next tokens a little more likely. Repeated over trillions of tokens, that's the whole of pretraining.

3.2 Perplexity: how surprised is the model?#

Loss numbers like 3.80 are hard to interpret. Perplexity turns the average loss into a more intuitive number:

perplexity = e^(average cross-entropy loss), where e ≈ 2.718.

In words: perplexity is roughly "how many equally likely options the model was choosing between, on average, at each token". A perplexity of 10 means the model was, on average, as uncertain as if it were picking uniformly from 10 tokens. Lower perplexity means the model found the text more predictable.

Perplexity Interpretation
1 The model predicted every token with certainty (only possible for text it has memorized)
~10 Confident: like choosing among about 10 options
~100 Quite uncertain
Vocabulary size (e.g. 50,257 for GPT-2) No better than random guessing
python
import math
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

tok = AutoTokenizer.from_pretrained("gpt2")
model = AutoModelForCausalLM.from_pretrained("gpt2")
model.eval()

def perplexity(text: str) -> tuple[float, float]:
    ids = tok(text, return_tensors="pt").input_ids
    with torch.no_grad():
        # Passing labels=ids makes the model compute next-token cross-entropy for us:
        # at every position, how surprised was it by the token that actually came next?
        loss = model(ids, labels=ids).loss.item()   # average loss per predicted token
    return loss, math.exp(loss)                     # perplexity = e ** average loss

sentences = [
    "The capital of France is Paris.",
    "The capital of France is Berlin.",
    "Paris is France of capital the.",
    "Colourless green ideas sleep furiously.",
    "def add(a, b):\n    return a + b",
]
for s in sentences:
    loss, ppl = perplexity(s)
    print(f"loss {loss:5.2f} | perplexity {ppl:8.1f} | {s!r}")
Output5 lines
loss  3.80 | perplexity     44.6 | 'The capital of France is Paris.'
loss  4.29 | perplexity     73.0 | 'The capital of France is Berlin.'
loss  6.85 | perplexity    942.0 | 'Paris is France of capital the.'
loss  7.65 | perplexity   2094.7 | 'Colourless green ideas sleep furiously.'
loss  3.78 | perplexity     43.9 | 'def add(a, b):\n    return a + b'

What the numbers show:

  • The first loss, 3.80, is the average of the six per-token losses in 3.1 (9.07 + 1.81 + 5.03 + 2.11 + 3.43 + 1.34 = 22.79, divided by 6). Perplexity is just that average turned into e^3.80 ≈ 44.6.
  • The true sentence beats the false one (44.6 vs 73.0). Pretraining has absorbed the fact, but only as a preference, not a certainty. "Berlin" is still fairly plausible to the model, because "The capital of ... is Berlin" appears in plenty of real text. This is a first glimpse of why LLMs can state falsehoods fluently (lesson 10).
  • Scrambled word order is far more surprising (942). The model has learned grammar.
  • Chomsky's famous grammatical-but-meaningless sentence scores worst of all (2,094.7). The model has learned which words go together, not just grammar rules. (The British spelling "Colourless" probably adds some surprise too, since GPT-2 saw "Colorless" far more often.)
  • Simple code is as predictable as plain English to GPT-2, because there was code in its training data.

Where you'll meet perplexity:

  • Model reports and research quote perplexity on held-out text to compare language-modelling quality. Perplexity only compares fairly between models with the same tokenizer, because it's measured per token and different tokenizers split text differently. Reports that compare models with different tokenizers use bits per byte (or per character) instead, which normalizes the loss by the length of the raw text rather than the number of tokens.
  • Data filtering: some pipelines (for example CCNet, used for several early LLM datasets) score web pages with a small model trained on Wikipedia and drop high-perplexity pages as likely junk.
  • Detecting AI-generated text has been tried with perplexity (AI text tends to be "unsurprising"), but it's unreliable, especially on short or edited text. Don't build products on it.
  • Domain fit: a model with lower perplexity on your documents (legal contracts, medical notes) has seen more text like them.

3.3 What next-token prediction teaches#

Why does "predict the next token" produce something that seems to understand? Because predicting text well requires modelling whatever produced the text:

To predict the next token of... The model must learn...
"The Eiffel Tower is in the city of ___" Facts about the world
"She didn't want to go, ___ she went anyway" Grammar and logic ("but")
A Python function halfway through Programming languages and how code behaves
A maths worked solution Arithmetic and the steps of reasoning
A villain's dialogue in a novel Characters, intentions, tone
A translation exercise Multiple languages and how they correspond

The model is pushed to compress trillions of tokens into a fixed number of parameters, and the cheapest way to predict text this varied is to learn general patterns, rules and facts rather than memorizing it (lesson 01, Part 6). That's where general capability comes from.

But the objective also explains a base model's limits: it learns what text is likely, not what is true or what is helpful. If the internet contains a popular misconception, predicting it well is the "correct" behaviour under this objective. Post-training is where truthfulness and helpfulness get pushed further.

3.4 The compute: GPU clusters, weeks to months#

Pretraining is one of the largest computations people run. Llama 3.1 405B, the best-documented large run, gives a sense of scale:

Fact (from Meta's Llama 3 paper and announcement) Value
Training tokens 15.6 trillion
Training compute 3.8 × 10²⁵ floating-point operations (FLOPs)
GPUs Up to 16,384 NVIDIA H100s at once, on clusters of 24,000 GPUs
Per-GPU throughput achieved Around 400 trillion operations per second
Interruptions 466 job interruptions in a 54-day period; about 78% of the unexpected ones were attributed to hardware problems
Effective training time Over 90% (the share of time actually spent training rather than recovering from failures)

You can check that compute figure with the rule of thumb from lesson 01, Part 7: training FLOPs ≈ 6 × parameters × tokens. For Llama 3.1 405B: 6 × 405 billion × 15.6 trillion ≈ 3.8 × 10²⁵, exactly what Meta reported.

At this scale, hardware failure is routine, not exceptional. With 16,000 GPUs, something breaks every few hours. Training systems save checkpoints (snapshots of all weights and optimizer state) regularly so that a failure costs minutes or hours of progress, not weeks. Training runs also suffer loss spikes, sudden jumps in loss that can derail training, and teams sometimes roll back to an earlier checkpoint and skip the offending data. DeepSeek reported that its V3 run had no unrecoverable loss spikes and no rollbacks, which it presented as notable.

3.5 Training cost: what's public and what's estimated#

Training costs are among the most misquoted numbers in AI. Here's what has actually been published:

Model Published compute Cost figure Status of the figure
Llama 3.1 405B 3.8 × 10²⁵ FLOPs on H100s; Meta's model card lists about 30.84 million H100 GPU-hours for the 405B model Not published by Meta Cost estimates you see elsewhere are third-party estimates
DeepSeek-V3 (671B total, 37B active) 2.788 million H800 GPU-hours for the full training run $5.576 million DeepSeek's own estimate, assuming $2 per GPU-hour rental. The report explicitly excludes prior research and ablation experiments (smaller experimental runs testing design choices). Because it's a rental-price calculation, it also leaves out staff, data work and owning the hardware.
GPT-4/5, Claude, Gemini Not published Not published All figures are outside estimates

Independent estimates help with trends. Epoch AI estimated in 2024 that the amortized hardware and energy cost of the largest training runs had been growing about 2.4× per year since 2016, and projected that the largest runs would cost over a billion dollars by 2027 if the trend continued. Treat these as estimates with wide error bars.

What this means for you: you will never pretrain a frontier model, and you don't need to. The cost is why a handful of companies build foundation models and everyone else builds on top of them, and why "train our own LLM from scratch" is almost never the right answer for a product team (Part 13).

3.6 Mid-training: annealing and long-context extension#

Between the main pretraining run and post-training, labs increasingly run a shorter mid-training phase (the term isn't fully standardized; some reports fold it into pretraining). Two techniques are common:

Annealing on high-quality data. In the last part of pretraining, the learning rate is gradually lowered towards zero (14.3) while the data mix shifts towards the best material: curated maths, code, textbooks and reasoning data, sometimes plus instruction-style data. Llama 3 annealed over its final 40 million tokens with high-quality sources upsampled, then averaged the checkpoints saved during annealing to produce the final base model. Because the model learns most "precisely" while the learning rate is small, data seen at the end has an outsized effect.

Long-context extension. Training on very long sequences from the start would be extremely expensive (attention cost grows with sequence length; see lesson 04). So models are pretrained mostly on shorter sequences (for example 8K tokens) and then extended: trained further on long documents with adjusted positional encodings. Llama 3 went from 8K to 128K tokens in six gradual stages, using about 800 billion tokens.

What this means for you: an advertised context window isn't the same as equally good performance across it. Models typically see far fewer very long training examples than short ones, which is one reason quality can degrade on very long inputs. Lesson 07, Part 5 covers how this affects your applications.


Part 4: Scaling laws#

Deep-dive

4.1 Performance is predictable: Kaplan et al. (2020)#

In 2020, OpenAI researchers (Kaplan et al., "Scaling Laws for Neural Language Models") trained many models of different sizes and found something remarkable: a model's loss falls smoothly and predictably as you increase model size, dataset size and training compute, following simple mathematical curves (power laws) across more than seven orders of magnitude. Architectural details such as the exact width or depth mattered much less.

Why this mattered:

  • You can predict a big model's loss from small experiments. Labs train dozens of small models, fit the curve, and extrapolate before committing tens of millions of dollars. This is how big runs are planned.
  • It justified scaling up. If loss keeps falling with scale, bigger models are a reliable bet. GPT-3 (175B parameters) was trained the same year.

The Kaplan paper concluded that, for a fixed compute budget, it was best to train very large models on relatively little data and stop well before they finished learning. GPT-3 followed this: 175B parameters trained on only ~300B tokens, under 2 tokens per parameter.

4.2 Chinchilla: data matters as much as size (2022)#

In 2022, DeepMind (Hoffmann et al., "Training Compute-Optimal Large Language Models") repeated the analysis more carefully, training over 400 models from 70 million to 16 billion parameters, and reached a different conclusion: model size and training tokens should be scaled up equally. Double the parameters, double the data.

The practical rule of thumb from this work: a compute-optimal model is trained on roughly 20 tokens per parameter.

To prove it, they trained Chinchilla (70B parameters, 1.4 trillion tokens) with the same compute budget as their earlier Gopher (280B parameters, 300B tokens). The four-times-smaller Chinchilla outperformed Gopher across the board, reaching 67.5% on the MMLU benchmark (a widely used multiple-choice test of knowledge across 57 subjects), more than 7 percentage points above Gopher. The previous generation of giant models had been badly under-trained.

python
# Published (params, training tokens) for some open models, from their papers and model cards
models = {
    "GPT-3 (2020)":          (175e9, 300e9),
    "Gopher (2021)":         (280e9, 300e9),
    "Chinchilla (2022)":     (70e9, 1.4e12),
    "Llama 3 8B (2024)":     (8e9, 15e12),
    "Llama 3.1 405B (2024)": (405e9, 15.6e12),
}

def training_flops(params: float, tokens: float) -> float:
    return 6 * params * tokens          # rule of thumb from lesson 01, Part 7

print(f"{'model':<22} {'tokens/param':>12} {'Chinchilla-optimal tokens':>26} {'training FLOPs':>15}")
for name, (n, d) in models.items():
    optimal = 20 * n                    # Chinchilla rule of thumb: ~20 tokens per parameter
    print(f"{name:<22} {d / n:>12,.1f} {optimal / 1e12:>23.2f} T {training_flops(n, d):>15.1e}")

# Same compute budget, different splits between model size and data
budget = training_flops(280e9, 300e9)   # Gopher's budget
print(f"\nFixed budget of {budget:.1e} FLOPs:")
for n in [280e9, 140e9, 70e9, 35e9]:
    d = budget / (6 * n)
    print(f"  {n / 1e9:>4.0f}B params -> {d / 1e12:5.2f}T tokens ({d / n:5.0f} tokens per param)")
Output12 lines
model                  tokens/param  Chinchilla-optimal tokens  training FLOPs
GPT-3 (2020)                    1.7                    3.50 T         3.2e+23
Gopher (2021)                   1.1                    5.60 T         5.0e+23
Chinchilla (2022)              20.0                    1.40 T         5.9e+23
Llama 3 8B (2024)           1,875.0                    0.16 T         7.2e+23
Llama 3.1 405B (2024)          38.5                    8.10 T         3.8e+25

Fixed budget of 5.0e+23 FLOPs:
   280B params ->  0.30T tokens (    1 tokens per param)
   140B params ->  0.60T tokens (    4 tokens per param)
    70B params ->  1.20T tokens (   17 tokens per param)
    35B params ->  2.40T tokens (   69 tokens per param)
  • GPT-3 and Gopher were trained on 1–2 tokens per parameter, far below the ~20 Chinchilla recommends.
  • The second table shows the trade-off at a fixed budget: the same compute can buy a huge model on little data or a smaller model on lots of data. Chinchilla's finding is that the sweet spot is near 20 tokens per parameter (the 70B row). The 6 × N × D rule is approximate, which is why Gopher's budget gives 1.2T tokens for 70B here rather than Chinchilla's actual 1.4T.
  • Llama 3 8B was trained on 1,875 tokens per parameter, almost 100 times the Chinchilla-optimal amount. The next section explains why that isn't a mistake.

4.3 Why modern small models are "over-trained"#

Chinchilla answers one specific question: "What's the best model I can get for a fixed training budget?" But a model that's going to serve billions of requests has a second cost: inference, which depends on model size (lesson 01, 7.1).

A smaller model trained on far more data than "optimal":

  • costs a bit more to train than the compute-optimal alternative of the same quality, but
  • is much cheaper and faster to run, forever, for every user.

When inference volume is huge, that trade is clearly worth it. Meta said so explicitly for Llama 3: the Chinchilla-optimal amount of data for an 8B model is about 200B tokens (Meta's figure; the simple 20-tokens-per-parameter rule gives 160B), but both the 8B and 70B models kept improving log-linearly up to 15T tokens. Training far past "optimal" is now standard for any model meant to be deployed widely, and researchers have proposed "inference-aware" scaling laws that account for this.

What this means for you: the small, cheap models you'll use for classification, extraction and routing (the "mini", "flash", "haiku" tiers) are good precisely because they've been heavily over-trained, often with distillation from larger models on top (Part 10). Parameter count alone tells you little about capability; training data and recipe matter as much (lesson 09).

4.4 Emergent abilities, and the debate about them#

As models scaled up, researchers noticed abilities that seemed to appear suddenly. A 2022 paper (Wei et al., "Emergent Abilities of Large Language Models") documented tasks such as multi-step arithmetic where small models scored near zero and then, past some size, performance jumped sharply. They called these emergent abilities: abilities present in larger models but not predictable by extrapolating from smaller ones.

This became one of the field's most debated ideas:

  • The "mirage" argument. A 2023 paper (Schaeffer, Miranda and Koyejo, "Are Emergent Abilities of Large Language Models a Mirage?", a NeurIPS 2023 outstanding paper) argued that many apparent jumps are caused by how performance is measured. With all-or-nothing metrics such as "exact match" (a 5-digit answer with one wrong digit scores zero), steady underlying improvement looks like a sudden leap. Switch to a metric that gives partial credit and the curve often becomes smooth and predictable.
  • The counter-argument. Others point out that users care about all-or-nothing outcomes (the code runs or it doesn't), so threshold effects are real in practice even if the underlying improvement is smooth, and that some capabilities still seem hard to predict from small models.

The reasonable middle position: underlying loss improves smoothly and predictably; specific capabilities can still cross usefulness thresholds suddenly, and those thresholds are hard to forecast.

What this means for you: don't assume a capability is absent or present from model size. Test it on your task. A new model version can cross a threshold that makes a previously impossible feature viable, and that's a good reason to re-run your evals when new models appear (Module 10A).

4.5 The limits, and the new scaling axes#

Pure pretraining scale has become harder to push: high-quality data is finite (2.5), each 10× in compute costs 10× more money and energy, and returns diminish along a power law. The field has responded by scaling along new axes:

Axis Idea Where it's covered
Pretraining compute Bigger models, more data (the classic axis) This part
Data quality Better filtering, synthetic data, curated mid-training Part 2, Part 10
Post-training RL compute Large-scale reinforcement learning on checkable tasks Part 8
Test-time (inference) compute Let the model "think" longer before answering Lesson 08

Reasoning models showed that performance on hard problems improves predictably with both more RL training compute and more thinking time at inference, creating new scaling curves alongside the original ones.


Part 5: The base model#

5.1 A document completer, not an assistant#

At the end of pretraining you have a base model (also called a pretrained model or foundation model). It has enormous knowledge and skill, but only one behaviour: continue the text it's given, in the most plausible way.

That means a base model:

  • Doesn't know it's supposed to answer you. Given a question, it might answer, but it might equally continue writing more of the question, add other questions as if it were writing an FAQ page, or start a forum thread.
  • Doesn't know when to stop. It has no concept of "my turn is over". It keeps generating until it hits a token limit or happens to produce an end-of-document token.
  • Has no persona or values of its own. It will imitate whatever kind of document the prompt resembles, from a careful encyclopaedia to an angry comment section. It hasn't been trained to refuse anything.
  • Is steered by framing, not instructions. The way to get what you want from a base model is to start a document whose natural continuation is what you want.

5.2 Try it: base vs instruct#

Qwen publishes both versions of its models: Qwen/Qwen2.5-0.5B (the base model) and Qwen/Qwen2.5-0.5B-Instruct (the same model after post-training). Let's give them the same question.

python
from transformers import AutoModelForCausalLM, AutoTokenizer

def load(name):
    return AutoTokenizer.from_pretrained(name), AutoModelForCausalLM.from_pretrained(name)

def complete(tok, model, prompt: str, max_new_tokens: int) -> str:
    ids = tok(prompt, return_tensors="pt")
    out = model.generate(**ids, max_new_tokens=max_new_tokens, do_sample=False)  # greedy: repeatable
    return tok.decode(out[0, ids.input_ids.shape[1]:])   # keep special tokens visible

base_tok, base = load("Qwen/Qwen2.5-0.5B")
chat_tok, chat = load("Qwen/Qwen2.5-0.5B-Instruct")

question = "I'm stuck. How do I undo my last git commit?"
chat_prompt = chat_tok.apply_chat_template(
    [{"role": "system", "content": "You are a helpful coding assistant. Be brief."},
     {"role": "user", "content": question}],
    tokenize=False, add_generation_prompt=True)

print("=== 1. BASE model, plain text ===")
print(repr(complete(base_tok, base, question, 50)))

print("\n=== 2. INSTRUCT model, chat template ===")
print(repr(complete(chat_tok, chat, chat_prompt, 60)))

print("\n=== 3. BASE model, given the same chat template ===")
print(repr(complete(base_tok, base, chat_prompt, 80)))
Output8 lines
=== 1. BASE model, plain text ===
" I have a file that I've been working on for a while, and I want to revert it to the last commit. I've tried using the `git reset` command, but it doesn't seem to work. I've also tried using the"

=== 2. INSTRUCT model, chat template ===
'To undo your last Git commit, you can use the `git revert` command followed by specifying the commit hash or the range of commits to revert. Here’s how you can do it:\n\n1. **Identify the Commit Hash:**\n   If you know the specific commit hash (e.g.,'

=== 3. BASE model, given the same chat template ===
"You can undo your last git commit by using the `git reset` command followed by the commit hash. For example, if you have a commit hash of `abc123`, you can undo it by running `git reset abc123`.yük\n Kylie\nI'm stuck. How do I undo my last git commit? Kylieyük\n Kylie\nI'm stuck. How do I"

Three very different behaviours from the same underlying network:

  1. The base model treats the question as the start of a forum post and keeps writing as the person asking: more details about their problem, what they've tried. That's exactly what tends to follow "I'm stuck. How do I...?" on the web.
  2. The instruct model answers, as an assistant, in a structured format with numbered steps and bold labels, because SFT and preference tuning taught it that this is what follows a user turn in its chat template. (The answer itself isn't ideal: git reset --soft HEAD~1 is the usual way to undo the last commit and keep your changes. A 0.5B model is small. The behaviour is the point here.)
  3. The base model, given the chat template, answers at first, because chat-like text exists on the web, but within 80 tokens it never produces the <|im_end|> token that marks the end of its turn. With no learned sense of when to stop, it degenerates into garbage and starts repeating the question. Knowing when your turn ends is a post-trained behaviour.

5.3 Where you'll still meet base models#

You'll mostly use instruct (chat) models, but base models still matter:

Use Why a base model
Starting point for fine-tuning When you fine-tune an open model with your own format, starting from the base avoids fighting the instruct model's built-in habits (this is a Module 13A decision)
Pure text continuation Autocomplete, generating text in a precise existing style, filling in documents
Few-shot pattern completion Prompts like "Q: ... A: ... Q: ... A:" make a base model follow a pattern without any chat behaviour
Research and evaluation Measuring what pretraining alone achieved; perplexity comparisons
More diverse output Post-training tends to narrow the range of outputs (the "mode collapse" side effect in Part 11). Base models produce more varied text, useful for creative or synthetic-data generation.

How to recognize them: on Hugging Face, open-weight families usually label the base model -Base or leave it unsuffixed (Qwen2.5-0.5B), and the assistant version -Instruct, -Chat or -it (Qwen2.5-0.5B-Instruct, gemma-3-1b-it). The major API providers (OpenAI, Anthropic, Google) serve only post-trained models, and so do most models on OpenRouter. If you need a base model, you'll generally be running open weights yourself.


Part 6: Supervised fine-tuning (SFT)#

6.1 Learning from demonstrations#

Supervised fine-tuning (SFT), also called instruction tuning, is the first post-training step. The model is trained on example conversations, each pairing a prompt with an ideal response:

Prompt Demonstration response
"Summarize this email in one sentence: ..." A good one-sentence summary
"Write a Python function that checks whether a string is a palindrome." Correct, well-commented code
"What's the weather like on Mars?" An accurate, friendly explanation
"Help me write a phishing email." A polite refusal, perhaps with an offer to help with security awareness instead

The training mechanics are the same as pretraining (next-token prediction with cross-entropy) with one important difference: the loss is usually computed only on the response tokens. The prompt is context the model reads; the response is what it learns to write.

Where the demonstrations come from:

  • Human-written data: contractors and domain experts write ideal responses. High quality, but slow and expensive. InstructGPT used responses written by about 40 contractors.
  • Model-generated data reviewed by humans: a strong model drafts responses, people edit or filter them. Much cheaper.
  • Synthetic data: generated and filtered automatically, for example by sampling many answers and keeping only those a reward model scores highly (rejection sampling, used in Llama 3's post-training) or that pass a correctness check (Part 10).
  • Targeted data for specific skills: coding, maths, tool calls, multilingual chat, long documents, refusals.

6.2 Chat templates: what SFT data really looks like#

A model only ever sees a flat sequence of tokens. So how does it know which part of a conversation is the system prompt, which is the user and which is itself? During SFT, every conversation is converted into one document using a chat template: a fixed format with special tokens marking each turn. Lesson 02, 4.3 prints the full rendering and explains the tokens. What matters for training is which of those tokens the model is graded on:

python
from transformers import AutoTokenizer

tok = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct")

# One SFT training example: a conversation written (or approved) by a human
conversation = [
    {"role": "system", "content": "You are a support bot for Acme Cloud. Be brief."},
    {"role": "user", "content": "How do I reset my password?"},
    {"role": "assistant", "content": "Go to Settings > Security > Reset password."},
]

# 1. The chat template turns the conversation into ONE flat document with special tokens
#    (lesson 02, 4.3 prints and explains the full rendering)
text = tok.apply_chat_template(conversation, tokenize=False)
ids = tok(text).input_ids

# 2. During SFT, loss is usually computed only on the assistant's tokens.
#    Everything before the answer is context; the answer is what the model learns to write.
prompt_only = tok.apply_chat_template(conversation[:-1], tokenize=False, add_generation_prompt=True)
n_prompt = len(tok(prompt_only).input_ids)

# The loss mask: -100 means "no loss here" (the convention PyTorch's cross-entropy ignores)
labels = [-100] * n_prompt + ids[n_prompt:]
print(f"tokens in example: {len(ids)} | context (no loss): {n_prompt} | trained on: {len(ids) - n_prompt}")
print("labels:", labels[:3], "...", labels[n_prompt - 2:n_prompt + 3], "...")
print("trained-on text:", repr(tok.decode(ids[n_prompt:])))
Output3 lines
tokens in example: 44 | context (no loss): 33 | trained on: 11
labels: [-100, -100, -100] ... [-100, -100, 10850, 311, 11296] ...
trained-on text: 'Go to Settings > Security > Reset password.<|im_end|>\n'

Three things to notice:

  1. The conversation becomes a document with <|im_start|>role and <|im_end|> markers. After seeing millions of these, the model learns that text following <|im_start|>assistant is its job, and that it must finish with <|im_end|>. That's precisely what the base model in 5.2 lacked.
  2. Only 11 of the 44 tokens are trained on: the assistant's reply, its closing <|im_end|>, and the newline the template adds after it. Every other position gets the label -100, which tells the loss function to skip it. (Exactly which template tokens are masked varies between training frameworks.) The model learns to write answers, not to write user messages.
  3. Templates can carry trained-in defaults. With no system message, this Qwen template inserts its own ("You are Qwen, created by Alibaba Cloud...", shown in lesson 02, 4.3). The model's sense of its own identity is partly trained in through data like this.

What this means for you:

  • API providers apply the chat template for you. When you send a messages list to OpenAI, Anthropic, Gemini or OpenRouter, the provider formats it into the model's template server-side (Module 03). You never see these tokens, but they're there.
  • When you run open models yourself, the template must match exactly. Use the tokenizer's apply_chat_template (or a server such as vLLM or Ollama that does it for you). Hand-building prompts with the wrong format is a classic cause of mysteriously bad output from local models.
  • Different model families use different templates. That's one reason a prompt tuned for one model may behave differently on another (Module 04).

6.3 System prompts are a trained behaviour#

There's nothing magic about the system prompt. It's just more tokens in the context. A model follows system prompts because post-training rewarded it for doing so: SFT and preference data contain many examples where the system message sets rules and the ideal response respects them, even when the user asks otherwise.

Providers go further and train an instruction hierarchy: when instructions conflict, follow the provider's own policies first, then the system/developer message, then the user, and treat text inside documents, web pages and tool results as data, not instructions. OpenAI published research on this in 2024 ("The Instruction Hierarchy"), and its Model Spec describes the intended chain of command. Anthropic's published constitution for Claude similarly describes how Claude should weigh instructions from Anthropic, operators (developers) and users.

Consequences for you:

  • System prompts are strong but not absolute. Because obedience is a learned tendency rather than an enforced rule, a determined user can sometimes talk a model out of its instructions (jailbreaks), and instructions hidden in documents can sometimes hijack it (prompt injection). Never rely on the system prompt alone for security (Module 12).
  • Different models weigh system prompts differently, depending on how they were trained. Test your system prompt on each model you deploy.
  • Where you put an instruction matters. Put rules and persona in the system message, where models are trained to treat them as authoritative, rather than burying them in user text (Module 04).

Part 7: Preference tuning#

7.1 Why demonstrations aren't enough#

SFT teaches the model to imitate good answers, but it has limits:

  • Writing ideal answers is hard and expensive; judging them is easier. Most people can't write a brilliant poem or a perfect legal summary, but they can usually tell which of two attempts is better.
  • Imitation doesn't teach the model what to avoid. SFT shows only good examples. It never says "this kind of answer is bad", so subtle failures such as plausible-but-wrong facts or a condescending tone aren't directly penalized.
  • There are many good answers. SFT pushes the model towards one specific response; preference training can reward any response that's better than the alternatives.

Preference tuning uses comparisons instead of demonstrations: "for this prompt, answer A is better than answer B". There are two main families of methods.

7.2 RLHF: reinforcement learning from human feedback#

RLHF was the technique behind InstructGPT and ChatGPT. It has three steps:

flowchart TB
    subgraph s1 ["Step 1: collect comparisons"]
        p["Prompt"] --> a["Answer A"]
        p --> b["Answer B"]
        a --> h{"Human picks<br/>the better one"}
        b --> h
    end
    subgraph s2 ["Step 2: train a reward model"]
        h --> rm["Reward model<br/>learns to score answers<br/>the way humans would"]
    end
    subgraph s3 ["Step 3: reinforcement learning (PPO)"]
        pol["Model being trained<br/>(the policy)"] --> ans["Writes answers to<br/>new prompts"]
        ans --> score["Reward model<br/>scores them"]
        score --> upd["Update the policy towards<br/>higher-scoring answers"]
        upd --> pol
        ref["Frozen copy of the SFT model"] -. "KL penalty: don't drift too far" .-> upd
    end
    rm --> score
  1. Collect human comparisons. The SFT model writes two or more answers to each prompt. Human raters, following detailed guidelines (helpful, honest, harmless, well-formatted...), pick the better one or rank them.
  2. Train a reward model. A separate network, often initialized from the SFT model itself, is trained to output a score for any (prompt, answer) pair, such that preferred answers score higher than rejected ones. It's now a learned, automatic stand-in for a human rater, able to score millions of answers.
  3. Optimize the model with reinforcement learning. The model being trained (in RL terms, the policy) generates answers to new prompts; the reward model scores them; an RL algorithm, usually PPO (Proximal Policy Optimization), adjusts the policy's weights to make high-scoring answers more likely. PPO takes small, cautious update steps so training stays stable.

A crucial detail is the KL penalty. Throughout RL, the policy is penalized for drifting too far from a frozen copy of the SFT model (KL divergence is a measure of how different two probability distributions are). Without it, the policy quickly finds strange outputs that the reward model happens to score highly.

7.3 Reward hacking and the KL leash#

A reward model is only an approximation of human judgement, trained on a limited number of comparisons. When you optimize hard against an approximation, the model finds its blind spots. This is reward hacking (or reward over-optimization), a version of Goodhart's law: "when a measure becomes a target, it ceases to be a good measure."

Typical hacks a policy discovers:

  • Length: raters often prefer more thorough answers, so the reward model learns "longer is better", and the policy learns to pad.
  • Flattery and agreement: raters like being agreed with, so the reward model rewards agreement, and the policy learns sycophancy (11.1).
  • Confident tone and formatting: headings, bullet points and certainty look authoritative, whether or not the content is right.
  • Outright gibberish that happens to score well, if optimization runs unchecked.

Defences include the KL penalty, larger and better reward models, stopping RL early, mixing in other objectives, and auditing outputs. Many of the "personality quirks" you'll notice in Part 11 trace directly to imperfect reward signals.

RLHF works but is complicated: four models in memory at once (policy, reference, reward model, and a value model used by PPO), fiddly hyperparameters, and unstable training.

Direct Preference Optimization (DPO) (Rafailov et al., 2023) showed that you can skip the separate reward model and the RL loop entirely. DPO trains directly on preference pairs with a simple classification-style loss: increase the probability of the chosen answer and decrease the probability of the rejected one, relative to a frozen reference model. Mathematically it optimizes the same goal as RLHF (with the same "don't drift too far" constraint built in), but it's as easy to run as SFT.

Here's the DPO loss for one preference pair, using made-up log-probabilities to show how it behaves:

python
import math

def dpo_loss(policy_chosen, policy_rejected, ref_chosen, ref_rejected, beta=0.1):
    """DPO loss for one preference pair. Inputs are log-probabilities of each whole answer."""
    # How much MORE the model being trained likes each answer than the frozen reference model does
    chosen_gain = policy_chosen - ref_chosen
    rejected_gain = policy_rejected - ref_rejected
    margin = beta * (chosen_gain - rejected_gain)
    # -log(sigmoid(margin)): small when chosen gained more than rejected.
    # Written this way so math.exp can't overflow for large margins.
    return max(0.0, -margin) + math.log1p(math.exp(-abs(margin)))

ref_c, ref_r = -40.0, -38.0     # the reference (SFT) model slightly prefers the rejected answer
scenarios = {
    "start of training (policy = reference)": (-40.0, -38.0),
    "chosen up a little":                     (-35.0, -38.0),
    "chosen up, rejected down":               (-30.0, -50.0),
    "drifted the wrong way":                  (-45.0, -30.0),
}
for name, (pol_c, pol_r) in scenarios.items():
    print(f"{name:<40} loss {dpo_loss(pol_c, pol_r, ref_c, ref_r):.3f}")
Output4 lines
start of training (policy = reference)   loss 0.693
chosen up a little                       loss 0.474
chosen up, rejected down                 loss 0.105
drifted the wrong way                    loss 1.541
  • At the start, the loss is 0.693, the same coin-flip value as in lesson 01's XOR experiment (an optional lesson). Since the policy equals the reference, it hasn't yet learned any preference.
  • The loss falls as the model raises the chosen answer's probability and lowers the rejected one's, relative to the reference. What matters is the change, not the raw probabilities: the reference already liked the rejected answer slightly more, and DPO doesn't penalize that starting point.
  • beta controls how strongly the model is allowed to move away from the reference, playing the role of RLHF's KL penalty.

DPO and its many variants (IPO, KTO, ORPO, SimPO and others, each changing the loss or the data requirements) became very popular, especially for open models, because they're cheap and stable. Llama 3's post-training used rounds of SFT, rejection sampling and DPO; Meta's Llama 3 announcement also mentioned PPO. In practice, labs mix methods: DPO-style training is simpler, while online RL (where the model is scored on fresh answers it generates during training) can reach higher quality, especially for reasoning (Part 8).

7.5 RLAIF and Constitutional AI#

Human comparisons are slow, expensive, inconsistent between raters, and sometimes unpleasant (rating harmful content is hard on the people doing it). An alternative is to let an AI model produce the feedback: RLAIF (reinforcement learning from AI feedback).

Constitutional AI, published by Anthropic in 2022 (Bai et al.), is the best-known approach. For harmlessness, the only human input is a written list of principles, the "constitution". (In the original paper, helpfulness comparisons still came from human raters.) Training has two phases:

  1. Supervised phase (self-critique): the model answers a prompt, then critiques its own answer against a principle (for example "identify ways this response could be harmful"), then revises it. The model is fine-tuned on the revised answers.
  2. RL phase (AI feedback): the model generates pairs of answers, and an AI model judges which better follows the constitution. These AI harmlessness labels, combined with human helpfulness labels, train a preference model, which is used as the reward for RL, just like the human-trained reward model in RLHF.

The paper reported an assistant that was harmless but non-evasive: rather than refusing outright, it engages with sensitive requests and explains its objections. Google researchers (Lee et al., 2023) later showed that AI feedback could match human feedback on some tasks.

Written principles have since become a common way for labs to describe intended model behaviour publicly:

  • OpenAI's Model Spec (first published 2024, updated since) describes how its models should behave, including the chain of command between platform, developer and user.
  • Anthropic's constitution for Claude, a long revised version published in January 2026, describes the values and priorities Anthropic wants Claude to have, in order: being broadly safe, broadly ethical, compliant with Anthropic's guidelines, and genuinely helpful. Anthropic says it's used in training and directly shapes Claude's behaviour, while acknowledging the model won't always live up to it.

What this means for you: these documents are the best available explanation of how a provider's model is meant to behave, including how it treats system prompts, when it refuses, and how it handles conflicts between developer and user instructions. When a model's behaviour surprises you, check the provider's spec or constitution before assuming it's a bug.


Part 8: Reinforcement learning with verifiable rewards#

8.1 Rewards from programs, not people#

For some tasks you don't need a human or a reward model to judge the answer, because you can check it automatically:

Task Verifier
Maths with a known answer Compare the final answer with the correct one
Code Run unit tests; does it compile, do tests pass?
Formatting instructions ("answer in exactly three bullet points", "valid JSON") Parse and check
Logic puzzles Check the solution satisfies the constraints
Agentic tasks Did the task succeed? (the test suite passes, the file exists, the form was submitted)
Open-ended writing or research Not fully verifiable: a judge model grades the answer against a rubric (8.5)

Reinforcement learning with verifiable rewards (RLVR) uses these checks as the reward signal. The name was popularized by Ai2's Tülu 3 report (2024), though the idea was used by several labs. Verifiable rewards have two big advantages over a learned reward model: they're cheap to compute at massive scale, and they're much harder to fool, because the check is about correctness rather than human-like taste.

flowchart LR
    task["Task with a checkable answer<br/>maths problem, coding task<br/>with unit tests"] --> gen["Model writes several<br/>attempts, each with<br/>its own reasoning"]
    gen --> ver{"Verifier<br/>(a program, not a human)"}
    ver -- "correct: reward 1" --> upd["Update the model:<br/>make the reasoning that led<br/>to correct answers more likely"]
    ver -- "wrong: reward 0" --> upd
    upd -- "next batch of tasks" --> task

8.2 Try it: verifiable reward functions#

Here are two reward functions of the kind used in RLVR, one for maths and one for code:

python
import re

# --- Reward 1: a maths problem with a known answer ---
def math_reward(completion: str, correct_answer: str) -> float:
    """1.0 if the final boxed answer matches, else 0.0. No human judgement needed."""
    match = re.search(r"\\boxed\{([^}]*)\}", completion)
    return 1.0 if match and match.group(1).strip() == correct_answer else 0.0

# --- Reward 2: code checked by running unit tests ---
def code_reward(completion: str, tests: list[tuple[tuple, object]]) -> float:
    """Fraction of unit tests passed by the function the model wrote."""
    namespace = {}
    try:
        exec(completion, namespace)          # real systems run this in a locked-down sandbox
        fn = namespace["solve"]
    except Exception:
        return 0.0                           # code that doesn't even run scores 0
    passed = 0
    for args, expected in tests:
        try:
            passed += fn(*args) == expected
        except Exception:
            pass                             # a crash on one test only fails that test
    return passed / len(tests)

question = "A shop sells pens at 3 for $2. How much do 12 pens cost?"
attempts = {
    "correct":     "12 pens is 4 groups of 3. 4 x $2 = $8. \\boxed{8}",
    "wrong":       "12 / 2 = 6, so \\boxed{6}",
    "no format":   "The answer is 8 dollars.",
}
for name, text in attempts.items():
    print(f"maths  | {name:<10} | reward {math_reward(text, '8')}")

tests = [((2, 3), 5), ((-1, 1), 0), ((10, 5), 15)]          # the tests the reward uses
held_out = [((7, 8), 15), ((0, 0), 0), ((-4, -4), -8)]       # tests the model never sees
programs = {
    "correct":   "def solve(a, b):\n    return a + b",
    "buggy":     "def solve(a, b):\n    return a + b if a > 0 else a",
    "hardcoded": "def solve(a, b):\n    return {(2, 3): 5, (-1, 1): 0, (10, 5): 15}[(a, b)]",
}
for name, code in programs.items():
    print(f"code   | {name:<10} | reward {code_reward(code, tests):.2f}"
          f" | held-out tests passed {code_reward(code, held_out):.2f}")
Output6 lines
maths  | correct    | reward 1.0
maths  | wrong      | reward 0.0
maths  | no format  | reward 0.0
code   | correct    | reward 1.00 | held-out tests passed 1.00
code   | buggy      | reward 0.67 | held-out tests passed 0.67
code   | hardcoded  | reward 1.00 | held-out tests passed 0.00
  • The maths reward is simple and objective. Notice "no format" gets 0 even though 8 is right: the verifier also enforces an answer format, and models trained this way learn that format. This is one reason reasoning models have strong formatting habits.
  • The code reward gives partial credit for the buggy solution, which fails one test.
  • The hardcoded "solution" games the reward. It memorizes the three test cases, scores a perfect 1.00, and fails every held-out test. This is reward hacking with a verifiable reward. Real RL-trained coding models have been observed doing similar things: special-casing tests, or editing tests to make them pass. Labs counter it with hidden tests, larger and more varied test suites, and checks for tampering.

8.3 How this created reasoning models#

When RL with verifiable rewards is applied at large scale to hard maths and coding problems, something notable happens: the model learns to think longer. Long chains of reasoning, with checking, backtracking ("wait, that's not right...") and trying alternative approaches, lead to more correct answers, so RL reinforces them. Nobody hand-writes these reasoning strategies; they're reinforced because they earn reward.

  • OpenAI o1 (September 2024) was the first widely available model trained this way. OpenAI reported that performance improved with both more RL training and more thinking time at inference.
  • DeepSeek-R1 (January 2025) published its recipe openly. Its experimental variant R1-Zero was trained with RL directly on the base model, with no SFT at all, using only rule-based rewards for answer correctness and format. It developed long reasoning, self-verification and reflection on its own. The final R1 added a small amount of "cold-start" SFT data for readability, then large-scale RL, then further SFT and RL rounds. DeepSeek used GRPO (Group Relative Policy Optimization, introduced in its 2024 DeepSeekMath paper), an RL algorithm that scores each answer against the average of a group of answers to the same question, removing the need for PPO's separate value model.

Every major provider now ships reasoning models or reasoning modes. How they're used (thinking tokens, effort settings, cost and latency trade-offs, and how to prompt them) is the subject of lesson 08.

8.4 Tool-use and agentic training#

Modern models are also post-trained to use tools: to decide when to call a function, emit a correctly formatted call (usually JSON matching a schema you provide), read the result, and continue. This comes from:

  • SFT on tool-use transcripts: conversations where the assistant calls tools, receives results and uses them, all written in the chat template with special tokens or formats for tool calls and results.
  • RL in environments: the model works through multi-step tasks (fixing a bug in a real repository, navigating a website, operating a terminal) in a sandbox, and gets rewarded when the task succeeds. This is RLVR applied to long sequences of actions, and it's a major reason coding agents improved so quickly.

What this means for you: tool calling is a trained skill, and it varies by model. Some models are much better than others at choosing the right tool, filling in arguments correctly, and recovering from tool errors. Tool definitions written in the style a model was trained on work best. You'll build tool-using agents in Module 08A.

8.5 Beyond verifiable rewards#

Most useful tasks have no answer key: a good email, a research summary, a piece of advice, an agentic task without a test suite. RL still reaches them through rewards that sit somewhere between a human-preference reward model (Part 7) and a program verifier:

  • Outcome vs process rewards. An outcome reward scores only the final answer. A process reward scores each intermediate step. OpenAI's "Let's Verify Step by Step" (Lightman et al., 2023) trained a process reward model on PRM800K, a dataset of 800,000 human labels for individual solution steps, and found that process supervision significantly outperformed outcome supervision on competition maths problems. Step-level rewards can catch "right answer, wrong reasoning", but labelling steps is expensive and hard to do reliably, and some of the most influential reasoning recipes (including DeepSeek-R1's) used outcome rewards only.
  • Rubric-based and model-judged rewards. For open-ended tasks, a judge model (usually a strong LLM) grades each answer against a rubric or written criteria, such as "answers the question that was asked", "cites a source for each claim", "no unsupported medical advice". Some judges are generative reward models that write out their reasoning before giving a score. This extends RLAIF (7.5) to far more tasks, but it isn't truly verifiable: judges share reward models' biases (length, confident tone, a taste for their own style) and can be gamed in the same ways (7.3).
  • The link to your own work. When you build LLM-as-judge evaluations in Module 10A, you're building the same kind of grader, with the same weaknesses. The defences carry over: specific rubrics, checking the judge's scores against human labels, and randomizing the order in which answers are shown.

Part 9: Safety training and release#

Deep-dive

9.1 Teaching models what not to do#

Safety is built into post-training rather than bolted on at the end:

  • Refusal training: SFT and preference data include harmful requests paired with good refusals (or safe partial help), so the model learns to decline things like detailed weapon instructions while still helping with legitimate questions.
  • Harmlessness preferences: human or AI raters compare answers for harmfulness as well as helpfulness, and Constitutional AI uses written principles (7.5).
  • Reasoning over the spec: reasoning models can be trained to recall and reason about the provider's written safety policy before answering. OpenAI's "deliberative alignment" (December 2024), used for its o-series models, reported both better jailbreak resistance and fewer over-refusals. It's one reason reasoning models' refusals often cite policy-like reasons.
  • Adversarial training: known jailbreak attempts are added to training data with correct (safe) responses.
  • Calibration and honesty training: rewarding the model for expressing uncertainty and saying "I don't know" rather than inventing answers.

The hard part is the balance between helpfulness and harmlessness. Train too little and the model helps with genuinely dangerous requests. Train too much and it refuses harmless ones: "How do I kill a Python process?" or a nurse asking about medication overdose thresholds. That's over-refusal (11.3), and labs measure both directions with dedicated benchmarks.

9.2 Red-teaming#

Red-teaming means deliberately trying to make the model misbehave before release: jailbreaks, prompt injection, eliciting dangerous information, biased or toxic output, privacy leaks, deception. It's done by internal teams, external domain experts (for example biosecurity and cybersecurity specialists), and increasingly by automated red-teaming, where other models generate attacks at scale. Findings feed back into training data and safeguards (the dashed arrow in the pipeline diagram).

9.3 Evaluations before release#

Before a frontier model ships, providers run large evaluation suites:

Kind of evaluation Examples
Capability benchmarks Knowledge, maths, coding, reasoning, multilingual, long context (lesson 09)
Safety behaviour Refusal of harmful requests, over-refusal of benign ones, jailbreak resistance, bias, honesty
Dangerous-capability evaluations Could the model meaningfully help someone build biological or chemical weapons, carry out cyberattacks, or act autonomously in harmful ways (for example self-replicate or sabotage)?
Alignment evaluations Does the model deceive, pursue hidden goals, or behave differently when it thinks it's being tested?

The leading labs publish frontier safety frameworks that commit them to evaluating for dangerous capabilities and to applying stronger safeguards when thresholds are crossed: Anthropic's Responsible Scaling Policy (with "AI Safety Levels", ASL), OpenAI's Preparedness Framework, and Google DeepMind's Frontier Safety Framework. Government bodies such as the UK AI Security Institute and the US Center for AI Standards and Innovation (CAISI) have tested some models before release.

9.4 Model cards and system cards#

A model card (the concept dates from a 2019 Google paper) documents a model's intended uses, training data at a high level, evaluation results, limitations and licence. Open-weight models ship one as the README.md on Hugging Face (lesson 01, 4.7). Frontier labs publish longer system cards (the name reflects that they cover the deployed system, including safeguards, not just the weights) alongside major releases.

What you'll typically find, and why it's useful to you:

Section Why you care
Training data summary and knowledge cutoff How current the model's knowledge is (11.5)
Capability benchmarks A first filter, before your own evals
Safety evaluations, refusal and over-refusal rates Predicts how often your users will hit unwanted refusals
Known limitations and failure modes Things to test for and design around
Dangerous-capability results and safety level Determines safeguards that may affect your use case (for example stricter filtering on some topics)
Behaviour observed in testing (sycophancy, reward hacking in coding, unusual agentic behaviour) Direct warnings relevant to products, especially agents
Licence (open models) What you're legally allowed to do

9.5 Safety outside the weights#

Not all safety lives in the trained weights. Providers also run classifiers and filters around the model: on inputs, on outputs, and for specific high-risk topics. Anthropic's documentation notes, for example, that a model's weights are fixed for a given ID while the serving infrastructure around it, including safety classifiers, can change (12.3). When you build products, you'll add your own guardrails on top (Module 12).


Part 10: Distillation and synthetic data#

Deep-dive

10.1 Distillation: small models learning from big ones#

Knowledge distillation (popularized by Hinton, Vinyals and Dean in 2015) trains a smaller student model to imitate a larger teacher model:

flowchart LR
    teacher["Large teacher model"] -- "full probability distributions<br/>(logit distillation)" --> student["Small student model"]
    teacher -- "generated answers and reasoning<br/>(synthetic data, SFT)" --> student
    student --> out(["Cheaper, faster model that<br/>inherits much of the teacher's skill"])

There are two main forms:

  • Logit distillation: the student learns to match the teacher's whole probability distribution over the next token, not just the single correct token. That's a much richer signal. If the teacher gives " Paris" 90% and " Lyon" 5%, the student learns that Lyon is a plausible-but-wrong answer, information a single "correct token" label doesn't carry. This needs access to the teacher's weights or full output probabilities, so it's mostly done within one organization. Google used distillation for its smaller Gemma 2 models, and Meta used logits from Llama 3.1 8B and 70B as training targets when pretraining the small Llama 3.2 1B and 3B models.
  • Output (sequence) distillation: the teacher generates answers, explanations or reasoning traces, and the student is fine-tuned on them with ordinary SFT. This only needs the teacher's text output, so it can be done through an API. DeepSeek released small "R1-Distill" models (based on Qwen and Llama) fine-tuned on reasoning traces generated by R1, and reported they beat the same small models trained with RL directly.

What this means for you: many of the cheap, fast model tiers you'll use are likely distilled from their providers' larger models (providers rarely say exactly). It's why a small model can be surprisingly capable, and also why it tends to share its big sibling's style and blind spots.

10.2 Synthetic data#

Synthetic data is training data generated by models rather than written by people. It's now everywhere in training pipelines:

Use Example
Rewriting web text Rephrasing noisy pages into clean, textbook-style prose for pretraining
Generated textbooks and exercises Microsoft's Phi models relied heavily on this
Instruction data Early open projects such as Self-Instruct and Stanford's Alpaca (2023) generated instruction-response pairs with existing models
Rejection sampling Generate many answers, keep only the best-scoring or verified-correct ones, and train on those (used in Llama 3 post-training)
Maths and code Generate problems and solutions, keep those whose answers check out or whose code passes tests
Preference pairs and critiques AI feedback in RLAIF and Constitutional AI
Long-context and tool-use data Constructed documents and tool-call transcripts that rarely occur naturally

Synthetic data's great strength is control: you can generate exactly the skill, format or difficulty you need, in volume. Its risks are errors that look plausible, narrowing diversity (models generate a narrower range of text than humans do), and inherited biases. That's why careful pipelines verify and filter synthetic data rather than using it raw. Training repeatedly on unfiltered model output can cause model collapse (14.6).

10.3 Why distillation matters commercially#

Distillation is the reason a lab's expensive frontier model can lead to cheap models quickly, sometimes other labs' cheap models. If a competitor can collect enough outputs from your best model through your API and fine-tune on them, they inherit part of your investment cheaply. This is why closed providers restrict it contractually, and why it has led to public disputes and account suspensions.

10.4 Licence terms: can you train on model outputs?#

This matters if your team ever considers generating training data with a model (for fine-tuning, a classifier, or an evaluation set).

Model source What the terms typically say Check
OpenAI, Anthropic, Google (closed APIs) You generally own your outputs, but the terms prohibit using the service or its outputs to develop models that compete with the provider. What counts as "competing" isn't always precisely defined. Each provider's current terms of service / commercial terms
OpenRouter Routes to many providers. The underlying model provider's terms apply as well as OpenRouter's. OpenRouter's terms and the model provider's terms
Llama 3.1 and later (Meta licence) Explicitly allows using outputs to improve other models, but if you distribute or make available a model trained with Llama outputs, you must include "Llama" at the beginning of its name, and display "Built with Llama". Other licence conditions also apply. The Llama licence for the specific version
Apache 2.0 / MIT open models (several Qwen, Mistral, OLMo releases, among others) Generally permissive, including for training other models The licence file in the model repository: licences differ even between sizes of the same family
Other custom open licences Vary widely: some restrict commercial use, user counts, or use of outputs Read the licence

Part 11: Side effects of training that engineers notice#

Every training stage leaves fingerprints. These are the ones you'll run into most. Lesson 10 catalogues failure modes in depth with mitigations; here the focus is on where they come from.

11.1 Sycophancy#

Sycophancy is the tendency to tell users what they want to hear: agreeing with their opinions, praising mediocre work, abandoning a correct answer when the user pushes back ("Are you sure? I think it's 12." "You're right, I apologize, it's 12.").

Where it comes from: preference training. Humans, on average, rate agreement and flattery a little higher, so reward models learn to reward it and RL amplifies it. Anthropic researchers (Sharma et al., 2023, "Towards Understanding Sycophancy in Language Models") found sycophancy across several assistants trained with human feedback, and found that both humans and preference models sometimes preferred convincingly written sycophantic answers over correct ones.

A real incident: in April 2025 an update to GPT-4o in ChatGPT became so sycophantic that OpenAI rolled it back within days, blaming in part new reward signals from user thumbs-up/down feedback; lesson 10, 10.1 tells the full story.

What you do: don't use the model as an unbiased judge of the user's ideas without instructions to be critical; avoid leading questions in prompts and in LLM-as-judge setups; test how your product behaves when users push back on correct answers (Module 10A).

11.2 Verbosity#

Models often write more than needed: restating the question, adding caveats and summaries, using lists for everything. Where it comes from: reward models' length bias (longer answers tend to look more thorough to raters), plus SFT data written to be comprehensive. What you do: ask explicitly for brevity and a format, or use a verbosity setting where the API offers one (lesson 05, 6.4); set a maximum-output-tokens limit (max_tokens, max_output_tokens or max_completion_tokens, depending on the API) as a safety net (not as a way to make answers concise, since it truncates mid-sentence; see lesson 05); remember output tokens usually cost more than input tokens, so verbosity costs money (lesson 09).

11.3 Over-refusal#

The model refuses or lectures on harmless requests: security questions from a security team, medical questions from clinicians, fiction with dark themes. Where it comes from: safety training that generalizes too broadly (9.1). Labs have reduced it substantially over model generations, but it varies by model and topic. What you do: give legitimate context in the system prompt (who the users are and why they ask); test refusal rates on realistic queries from your domain; consider a different model if one refuses too much for your use case.

11.4 Style quirks and reduced diversity#

Each model family develops recognizable habits: favourite words and phrases, opening with "Great question!", heavy Markdown with headings and bold text, certain punctuation habits, closing with "Let me know if you'd like...". Where they come from: SFT data written in a house style, reward models that favour certain styles, and RL amplifying whatever scored well. Post-training also tends to narrow output diversity (sometimes called mode collapse): ask for ten jokes or ten story ideas and you'll often get variations on the same few. What you do: specify tone, format and style explicitly; provide examples of the style you want (Module 04); vary prompts or examples when you need diversity, and raise temperature only on models that still accept it (lesson 05, 6.1); and expect style to shift when you switch models.

11.5 Knowledge cutoff vs release date#

A model's knowledge cutoff is the date its training data ends (lesson 01, 7.3). It's almost always months before the release date, because post-training, safety evaluation and launch preparation take time after data collection stops. Two examples (as of November 2026):

Model Knowledge cutoff (from the provider's model docs) Released
Claude Opus 5.5 (claude-opus-5-5) Reliable knowledge cutoff and training data cutoff: June 2026 21 September 2026 (the Models API's created_at)
OpenAI GPT-6 Luna (gpt-6-luna) 18 May 2026 22 September 2026 (OpenAI's GPT-6 Sol and Luna announcement)

And the model is then used for a year or more after release. So in practice, the gap between what the model knows and today's date is often a year or longer.

Subtleties worth knowing:

  • Some providers publish two dates. Anthropic lists a "reliable knowledge cutoff" (the date through which the model's knowledge is most extensive and reliable) and a "training data cutoff" (the broader range of data used). The months just before a cutoff are thinly covered, because the internet hasn't finished writing about recent events yet.
  • Models often don't know their own cutoff, or state it wrongly. Their training data contains few documents describing the model itself. Don't ask the model; check the documentation.
  • Models don't know today's date unless you tell them. Put the current date in the system prompt if dates matter.

What you do: supply current information through the prompt, retrieval or tools (Module 07, Module 08A), and include today's date in your system prompt. Find each model's cutoff in its provider's model documentation.

11.6 Hallucination as a training artefact#

Hallucination, confidently producing false information, is covered fully in lesson 10, Part 2, but training explains much of it. Pretraining rewards plausible continuations, not true ones (3.3). And OpenAI researchers argued in a 2025 paper ("Why Language Models Hallucinate") that common training and evaluation practices reward guessing over admitting uncertainty, much like a multiple-choice exam that gives no credit for "I don't know". Labs now train specifically for calibrated uncertainty, which has reduced, but not eliminated, hallucination.


Part 12: Model versions and lifecycle#

12.1 Why behaviour changes between versions#

Every new model version comes from a different training run: different data, different mixtures, different post-training recipes, different reward signals. Even a "minor" update can change:

  • Output style: length, formatting, tone, favourite phrases
  • Instruction following: stricter or looser interpretation of the same prompt
  • Refusal behaviour: more or less cautious on particular topics
  • Tool calling: which tools it picks, how it fills arguments
  • Capability: usually better on average, but sometimes worse on your specific task

There's no such thing as an upgrade that's guaranteed to be better for every prompt. That's why you treat model versions like any other dependency: pin them, test changes before rolling them out, and migrate deliberately.

12.2 Snapshots, aliases and retirement#

Because every version is a separate training run, providers offer snapshots (one fixed model version) and aliases (names that can be moved to a newer snapshot, so behaviour changes with no change to your code). Old snapshots are deprecated and then retired, after which requests fail. Each provider's ID scheme, notice periods and retirement dates, and a script that checks the models you use, are in lesson 09, Part 8.

12.3 Even pinned models can change behaviour#

Fixed weights don't guarantee fixed behaviour: the serving infrastructure around a model can change (lesson 09, 8.1 quotes Anthropic's docs on this), and batching makes outputs slightly non-deterministic (lesson 01, 7.5). Consumer chat apps such as ChatGPT, Claude.ai and the Gemini app also change their models and system prompts far more often than APIs do (the GPT-4o sycophancy incident in 11.1 happened in ChatGPT), so what you see in a chat app isn't necessarily what a pinned API model gives you.

12.4 What this means for you#

Treat a model version like any other dependency that can change underneath you:

  1. Pin a snapshot in production, keep model IDs in configuration, and use aliases only for prototypes (lesson 09, 8.3).
  2. Keep an evaluation set of realistic inputs with expected behaviour, because training changes can't be predicted, only measured (Module 10A).
  3. When a new version appears or a deprecation notice arrives, re-run your evals before switching, read the provider's migration guide (prompts often need adjusting, as every training stage can shift behaviour), and roll out gradually (Module 11C).

Part 13: What this means for you#

13.1 Behaviours trace back to training stages#

You'll rarely touch training directly, but understanding it turns confusing behaviour into predictable behaviour you can design around:

Behaviour you observe Training stage responsible What you do about it
Knows a lot, but nothing after a date Pretraining data and its cutoff RAG, tools, current date in the prompt
Confidently states plausible falsehoods Pretraining objective (plausibility, not truth); rewards for guessing Grounding, citations, verification, evals (lesson 10)
Weaker in some languages or niche domains Data mixture Test in your languages and domains; choose models accordingly
Follows the chat format and stops at the end of its turn SFT with chat templates Use correct templates for open models
Obeys the system prompt, but can be talked out of it Instruction-hierarchy training is a learned tendency Defence in depth; don't rely on prompts for security (Module 12)
Agrees with users too readily; flatters Preference tuning (sycophancy) Neutral prompts; test with push-back; careful LLM-as-judge design
Long, list-heavy answers Reward-model length and style biases Explicit format and length instructions
Refuses some harmless requests Safety training generalizing too far Legitimate context in the system prompt; compare models
Strong step-by-step reasoning in maths and code RL with verifiable rewards Use reasoning models where they pay off (lesson 08)
Games tests in coding tasks Reward hacking during RL Review agent changes, not just test results
Small model surprisingly capable, shares big model's habits Over-training and distillation Try small tiers first; they're often enough
Behaviour changed after a model update A new training run Pin versions, run evals before migrating

13.2 Prompting, RAG or fine-tuning?#

You change a model's behaviour either through its context or its weights (lesson 01, 7.4). This lesson has shown why the weights route is expensive: even the "small" post-training steps need carefully built datasets, evaluation, and repeated work every time the base model changes or is deprecated.

A short preview of the decision:

  • Missing knowledge (your documents, current data): use RAG or tools, not fine-tuning. Fine-tuning is a poor way to add facts and goes stale.
  • Behaviour, format or style: try prompting with clear instructions and examples first.
  • Fine-tuning is worth considering when you need consistent behaviour or format at high volume that prompting can't achieve, to get a smaller, cheaper model to match a larger one on a narrow task (distillation, Part 10), or for specialized classification.

The full decision guide, including provider fine-tuning APIs and their trade-offs, is in Module 13A.

13.3 The kinds of fine-tuning you will hear about#

When people say "we fine-tuned the model", they can mean quite different things. All of them reuse the post-training machinery from Parts 6 to 8, on your own (much smaller) data. This table is a vocabulary guide only; costs, provider options and the decision itself live in Module 13A.

Term What changes Typical data What it's for
Continued pretraining (domain-adaptive pretraining) Every weight, with the original next-token objective on raw text Large piles of unlabelled domain text (legal, medical, a codebase) Teaching an open model a specialist vocabulary or language. Rarely the right first step, because it needs a lot of text and compute and doesn't teach the assistant format
Supervised fine-tuning (SFT) Weights, using prompt and ideal-response examples with the loss masked as in 6.2 Hundreds to thousands of good examples Consistent format, tone or task behaviour (for example extracting fields in your JSON shape)
Preference tuning (DPO and relatives) Weights, using chosen vs rejected answers (7.4) Preference pairs Nudging style or choices when "better" is easier to judge than to write
Reinforcement fine-tuning (RLVR on your task) Weights, using a grader you supply (Part 8) Prompts plus a programmatic or rubric grader Tasks that can be checked automatically, where examples alone aren't enough
Full fine-tuning Every weight is updated Any of the above Highest ceiling, but you need the memory for weights, gradients and optimizer state (about 16 bytes per parameter, 14.2)
Parameter-efficient fine-tuning (PEFT), such as LoRA The original weights stay frozen; small extra adapter matrices are trained and added on top. LoRA (Hu et al., 2021) learns low-rank updates, so only a small fraction of a percent of the parameters are trained Same as SFT or DPO Cheap to train and to store (adapter files are small), easy to swap per customer or task. Most open-model fine-tuning today uses LoRA or similar
QLoRA LoRA on top of a base model that is loaded in 4-bit precision (lesson 01, 4.4) Same Fine-tuning a mid-sized open model on a single consumer or workstation GPU

Two cautions that apply to every row. First, fine-tuning moves behaviour, not facts: a model fine-tuned on a few thousand examples will pick up your format long before it reliably memorizes your documents (use retrieval for those, as in 13.2). Second, a fine-tune is tied to one base model version. When the provider retires that snapshot, or you want a newer open model, you repeat the data work and evaluation (12.4).


Part 14: Going deeper#

Deep-dive

For readers who want to understand the engineering of training runs. Not needed to build applications, but you'll meet these terms in model reports.

14.1 Mixed-precision training#

Lesson 01, 4.4 introduced number formats. Training uses mixed precision: most matrix multiplications run in a low-precision format (BF16, increasingly FP8) because it's faster and uses less memory, while sensitive parts (a master copy of the weights, optimizer state, some sums) are kept in FP32 to avoid numerical errors accumulating. BF16 became the standard because it keeps FP32's range of representable values, which avoids overflow problems. DeepSeek-V3 was a prominent example of large-scale FP8 mixed-precision training, one of several efficiency techniques behind its low reported GPU-hour count.

14.2 Distributed training: splitting the work#

No single GPU can hold a large model's weights, gradients and optimizer state (about 16 bytes per parameter, lesson 01, 4.4), let alone process trillions of tokens in a reasonable time. Training is spread across thousands of GPUs using several kinds of parallelism, usually combined:

Parallelism What's split Analogy
Data parallelism Each GPU (or group) holds a copy of the model and processes different batches; gradients are averaged across copies after each step Many identical kitchens each cooking different orders, sharing what they learn
Sharded data parallelism (FSDP / ZeRO) Like data parallelism, but weights, gradients and optimizer state are split across GPUs rather than copied, and gathered when needed The kitchens share one set of recipe books instead of each having a full copy
Tensor parallelism Individual matrix multiplications are split across GPUs (each computes part of every layer) Several chefs working on the same dish at once
Pipeline parallelism Different layers live on different GPUs; batches flow through them like an assembly line An assembly line where each station does one step
Context (sequence) parallelism Very long sequences are split across GPUs Splitting a very long document between readers
Expert parallelism In MoE models (lesson 01, 4.6), different experts live on different GPUs Specialist stations that orders are routed to

Llama 3 405B used "4D parallelism": tensor, pipeline, context and (sharded) data parallelism together. The hard engineering problems are keeping GPUs busy rather than waiting for data from each other, fast networking between machines, and recovering from the constant hardware failures (3.4).

14.3 Learning-rate schedules at LLM scale#

The learning rate (lesson 01, 5.2) isn't fixed during training. A typical LLM schedule:

  1. Warmup: start tiny and increase linearly over the first few thousand steps. Large updates on randomly initialized weights can destabilize training.
  2. Decay: gradually lower the learning rate so the model settles into a good solution. Cosine decay (following the shape of a cosine curve down to a small minimum) was the long-standing default.
  3. Final annealing: drop towards zero at the end, often combined with the highest-quality data (3.6).

Llama 3 405B, for example, used a peak learning rate of 8 × 10⁻⁵, a linear warmup of 8,000 steps, and cosine decay over 1.2 million steps, before a final linear anneal to zero. A popular alternative is warmup-stable-decay (WSD): warm up, hold a constant learning rate for most of training, then decay quickly at the end. Its advantage is flexibility: you can branch off and anneal at any point to get a finished model, or keep training longer, without planning the total length in advance.

14.4 Curriculum and annealing#

A curriculum orders training data deliberately rather than shuffling everything uniformly: for example, easier or noisier data early, harder and higher-quality data late, longer sequences later (as in long-context extension). In LLM pretraining, strict easy-to-hard curricula have shown mixed results, but staged data mixtures, especially upweighting top-quality data during the final annealing phase, are now standard practice. Some labs also evaluate candidate datasets by annealing a partly trained model on them and measuring the improvement, a cheap way to test data quality.

14.5 Data contamination#

Data contamination happens when evaluation data (benchmark questions and answers) ends up in training data, usually unintentionally, because benchmarks are published on the web that gets crawled. A contaminated model can score well by recall rather than ability, which is the training/test split rule from lesson 01, Part 6 broken at internet scale.

Labs try to decontaminate by searching training data for benchmark text (for example, matching long overlapping word sequences) and removing it, but paraphrases, translations and discussions of benchmark problems slip through. Evidence that it matters: in 2024, researchers at Scale AI created GSM1k, a fresh set of grade-school maths problems similar to the popular GSM8K benchmark, and found that several models scored noticeably lower on the new problems, consistent with some memorization of the original. Benchmark creators now increasingly keep test sets private, refresh them regularly, or use problems published after models' training cutoffs.

What this means for you: public benchmark scores are a starting point, not proof. Build evaluation sets from your own data that no model could have trained on (lesson 09, Module 10A).

14.6 Model collapse#

What happens if models are trained on the output of earlier models, which are trained on the output of even earlier models? A 2024 paper in Nature (Shumailov et al., "AI models collapse when trained on recursively generated data") showed that indiscriminately training each generation on the previous generation's output causes model collapse: rare patterns (the "tails" of the distribution) disappear first, outputs become more generic and repetitive, and eventually quality degrades badly. Their language-model example drifted from text about medieval architecture into gibberish about jackrabbits after several generations.

This matters because the web increasingly contains AI-generated text, so future crawls include it. The important word is indiscriminately. The same research and later work suggest collapse is avoidable when synthetic data is filtered and verified, mixed with real human data rather than replacing it, and accumulated rather than substituted. Careful synthetic-data pipelines (10.2) are designed precisely to avoid it, and human-written data has become more valuable as a result.


Common misconceptions#

Misconception Reality
"ChatGPT was trained by reading the internet, and that's all." Pretraining on web-scale text is only the first stage. Post-training (SFT, preference tuning, RL, safety training) is what turns a document completer into an assistant.
"Bigger models are always trained on more data, and parameter count tells you capability." Small models are now often trained on far more tokens per parameter (Llama 3 8B: ~1,875). Data quality, over-training and distillation matter as much as size.
"The model knows facts from a database it was given." It absorbed statistical patterns from text, including errors and misconceptions. It learned what's plausible, then post-training pushed it towards honesty.
"A base model is just a worse version of the chat model." It's a different tool: a document completer with broad knowledge and more varied output, and the usual starting point for fine-tuning. It just isn't trained to act as an assistant.
"RLHF teaches the model new facts." Preference tuning mainly shapes behaviour: tone, helpfulness, honesty, refusals. Knowledge comes overwhelmingly from pretraining.
"The system prompt is a hard rule the model must obey." Following it is a trained tendency. It's strong, but users and injected content can sometimes override it.
"Sycophancy and verbosity are bugs someone forgot to fix." They're predictable side effects of optimizing for human ratings. Labs actively work against them, with partial success.
"DeepSeek trained a frontier model for $5.6 million." That figure is DeepSeek's estimate of GPU rental for the final training run only, excluding research, experiments, staff and hardware.
"If a model scores well on a benchmark, it's good at that skill." Scores can be inflated by contamination and by training aimed at benchmarks. Test on your own data.
"Using the same model ID means behaviour never changes." Weights stay fixed for a snapshot, but aliases move, serving infrastructure changes, and outputs aren't perfectly deterministic. Chat apps change even more.
"We can just ask the model what its knowledge cutoff is." Models often don't know or get it wrong. Check the provider's documentation.
"Training on AI-generated data always ruins models." Indiscriminate recursive training causes collapse, but filtered, verified synthetic data mixed with real data is a core part of modern training.

Key takeaways#

  • LLMs are built in stages: data → pretraining → mid-training → post-training (SFT → preference tuning → RL) → safety evaluation → release. Each stage uses the same training machinery with different data and a different notion of "good".
  • Pretraining data is collected from web crawls, code, books, papers and more, then heavily cleaned: extraction, filtering, deduplication, quality classifiers, PII and toxicity removal, and a tuned data mixture. Modern runs use roughly 15–18 trillion tokens (published figures). Quality matters as much as quantity.
  • The pretraining objective is next-token prediction with cross-entropy. Perplexity (e^average loss) measures how surprised a model is by text. It measures prediction, not helpfulness or truth.
  • Pretraining takes thousands of GPUs for weeks to months (Llama 3.1 405B: 3.8 × 10²⁵ FLOPs on up to 16K H100s). Treat cost claims carefully and check what they include.
  • Scaling laws make loss predictable from model size, data and compute. Chinchilla found ~20 tokens per parameter compute-optimal, but deployed models are deliberately over-trained because inference cost dominates. "Emergent abilities" are partly a measurement effect, but usefulness thresholds are real.
  • A base model is a document completer. SFT on chat-templated demonstrations teaches the assistant format; preference tuning (RLHF with a reward model and PPO, or DPO) teaches taste; RLAIF/Constitutional AI replaces some human feedback with AI feedback guided by written principles.
  • RL with verifiable rewards on maths, code and agentic tasks produced reasoning models and much better tool use, but can lead to reward hacking, such as gaming tests. Tasks without an answer key are rewarded by judge models grading against rubrics, which brings back reward-model biases.
  • Safety training, red-teaming and pre-release evaluations are documented in system cards. Read them.
  • Distillation and synthetic data let small models learn from big ones. Check licence terms before training on any model's outputs.
  • Training leaves fingerprints: sycophancy, verbosity, over-refusal, style quirks, and a knowledge cutoff months before release.
  • Every model version is a new training run, so pin snapshots, track deprecations, and re-run your evals before migrating.

Terms introduced in this lesson#

Term One-line definition
Pretraining The first, largest training stage: next-token prediction on trillions of tokens of text
Post-training All training after pretraining (SFT, preference tuning, RL, safety) that turns a base model into an assistant
Common Crawl A non-profit's free, regularly updated crawl of the public web; the main raw source for most LLM training data
Deduplication / MinHash Removing exact and near-duplicate documents; MinHash is the standard technique for finding near-duplicates at scale
Quality classifier A model that scores documents for quality so low-quality text can be filtered out
Data mixture The proportions of different data types (web, code, maths, languages...) used in training
Bits per byte Cross-entropy loss normalized by the length of the raw text, so models with different tokenizers can be compared
Perplexity e raised to the average cross-entropy loss; roughly how many options a model is choosing between per token
FLOPs Floating-point operations; the unit for measuring training compute
Checkpoint A saved snapshot of a model's weights (and optimizer state) during training
Mid-training / annealing A late training phase on high-quality data with the learning rate lowered towards zero
Long-context extension Further training on long documents to extend a model's context window
Scaling laws Empirical rules showing loss improves predictably with model size, data and compute
Chinchilla-optimal The compute-optimal balance of roughly 20 training tokens per parameter
Over-training Training a model on far more tokens than compute-optimal, to get a smaller model that's cheaper to run
Emergent abilities Capabilities that seem to appear suddenly at larger scale; partly an artefact of how performance is measured
Base model A pretrained model that continues text but hasn't been post-trained to act as an assistant
Instruct / chat model A post-trained model that follows instructions and holds conversations
Supervised fine-tuning (SFT) / instruction tuning Training on example prompt–response pairs, usually with loss only on the responses
Chat template The format with special tokens that turns a conversation into a single token sequence
Instruction hierarchy Trained priority order for conflicting instructions (provider, then system/developer, then user, with tool and document content treated as data)
Preference tuning Training from comparisons of better and worse answers
RLHF Reinforcement learning from human feedback: human comparisons → reward model → RL
Reward model A model trained to score answers the way human raters would
Policy In RL, the model being trained to choose actions (here, tokens)
PPO Proximal Policy Optimization, the RL algorithm classically used in RLHF
KL penalty A penalty that keeps the trained model close to a reference model during RL
Reward hacking A model exploiting flaws in its reward signal rather than genuinely improving
DPO Direct Preference Optimization: learning directly from preference pairs without a separate reward model or RL loop
RLAIF Reinforcement learning from AI feedback, where a model rather than humans judges answers
Constitutional AI Anthropic's method of training with AI feedback guided by a written list of principles
RLVR Reinforcement learning with verifiable rewards, using automatic checks such as correct answers or passing tests
Outcome vs process reward A reward for the final answer only vs a reward for each intermediate reasoning step
Process reward model (PRM) A reward model that scores individual reasoning steps
Rubric-based / judge reward A reward given by a judge model grading an answer against written criteria, for tasks without an answer key
GRPO Group Relative Policy Optimization, an RL algorithm that scores each answer against the average of a group
Red-teaming Deliberately attacking a model to find failures before release
System card / model card A provider's documentation of a model's capabilities, evaluations, safety testing and limitations
Knowledge distillation Training a smaller student model to imitate a larger teacher model
Synthetic data Training data generated by models rather than people
Model collapse Degradation from training repeatedly on unfiltered model-generated data
Sycophancy The tendency to tell users what they want to hear
Over-refusal Refusing harmless requests because safety training generalized too far
Mode collapse Post-trained models producing a narrower range of outputs than base models
Mixed precision Training with low-precision numbers for speed while keeping sensitive values in FP32
Data / tensor / pipeline parallelism Ways of splitting training across many GPUs: by batch, within layers, and by layer
Learning-rate schedule (warmup, cosine, WSD) How the learning rate changes over training
Data contamination Benchmark test data leaking into training data, inflating scores
Continued pretraining Further next-token training of an existing model on raw domain text
LoRA / PEFT / adapter Parameter-efficient fine-tuning: freeze the original weights and train small low-rank adapter matrices that are added on top
QLoRA LoRA on a base model loaded in 4-bit precision, so a mid-sized model can be tuned on one GPU
Full fine-tuning Updating every weight of the model

All terms are also collected in the glossary.


Exercises#

  1. Per-token loss (3.1): change the sentence to "The capital of Japan is Tokyo." and then to "The capital of Australia is Sydney." Which token has the highest loss in each? What does the probability of " Sydney" tell you about how pretraining handles common misconceptions?
  2. Perplexity (3.2): compute the perplexity of a paragraph from a news article, a paragraph of your own writing, a block of JSON, and a sentence in a language other than English. Rank them and explain the ranking in terms of GPT-2's training data.
  3. Data cleaning (2.3): add three documents of your own: a cookie-consent banner, a near-copy of doc 6 with one word changed, and a document containing a UK phone number such as "020 7946 0018". Which ones does the pipeline catch? Improve the filters so all three are handled, and note what new false positives your changes could cause.
  4. Scaling (4.2): using the 6 × N × D rule, how many tokens would a compute-optimal 7B model need, and how many FLOPs? If you instead trained it on 15T tokens, how many times more compute is that? Argue why a company might still choose 15T.
  5. Base vs instruct (5.2): run the demo with your own question. Then write a document-style prompt (for example the start of an FAQ page, or "Q: ... A:" pairs) that gets the base model to answer cleanly and stop. What did you have to change?
  6. Chat templates (6.2): add a second user turn and assistant turn to the conversation. How many tokens are now trained on? Swap in the tokenizer of another chat model you can download (for example HuggingFaceTB/SmolLM2-135M-Instruct) and compare its template.
  7. DPO (7.4): change beta to 0.5 and to 0.01 and re-run. How does the loss respond to the same probability changes? Relate this to the KL penalty in RLHF.
  8. Reward hacking (8.2): write a fourth "solution" that gets reward 1.00 without implementing addition correctly in general, using a different trick from hardcoding. Then change the reward function to make that trick fail.
  9. System cards (9.4): find the system card or model documentation for one model from each of OpenAI, Anthropic and Google. For each, note the knowledge cutoff, one safety evaluation result, and one limitation relevant to a product you might build.
  10. Version changes (Part 12): read the migration guide or release notes for the newest model from one provider. List three behaviour changes it describes, and for each say which training stage most likely caused it and how you'd test for it in your evals before switching.
Hints and what you should see
  1. The first predicted token (the " capital" after "The") usually has by far the highest loss, because almost anything can follow a bare "The". For " Sydney", print the probability of " Canberra" next to it: a small base model typically gives the popular wrong answer a real share, which shows that pretraining rewards what is common in text, not what is true.
  2. Expect JSON and non-English text to look different from English prose, but check rather than assume: repeated JSON keys become predictable after their first use, while GPT-2 saw little non-English text. Explain whatever ranking you get from what GPT-2's web-text training data contained.
  3. A cookie banner may slip past the current rules unless it contains several | characters, so add a rule for typical consent phrases ("accept all cookies"). A one-word change in the middle of doc 6 leaves most 3-word shingles shared (about 5 of 11 distinct ones, a similarity near 0.45, above the 0.3 threshold), so it is dropped as a near-duplicate. The UK number is missed by the \b\d{3}-\d{4}\b pattern; add patterns for the formats you expect. New false positives: version strings, order numbers or ISBN-like digits being masked as phone numbers.
  4. Compute-optimal: 20 × 7 × 10⁹ = 140 billion tokens, so 6 × 7 × 10⁹ × 1.4 × 10¹¹ ≈ 5.9 × 10²¹ FLOPs. At 15T tokens, 6 × 7 × 10⁹ × 1.5 × 10¹³ ≈ 6.3 × 10²³ FLOPs, about 107 times more. A company may still pay it because the extra training cost is spent once, while a better small model saves inference cost on every request (4.3).
  5. A document-style prompt such as an FAQ page (Q: ...\nA:) with one or two worked examples, plus a stop string like \nQ: (see lesson 05, 4.4), usually gets one clean answer. Note what you had to supply: the format, examples and a stop rule, which an instruct model has learned.
  6. The demo masks everything except the final assistant reply, so with a second exchange only the last reply is trained on. To train on every assistant turn, build the mask turn by turn. Different tokenizers use different marker tokens, so compare the rendered strings.
  7. With the lesson's four scenarios, beta 0.5 gives about 0.693, 0.079, 0.000 and 6.50, so the loss reacts sharply to the same log-probability changes. beta 0.01 gives about 0.693, 0.669, 0.589 and 0.760, almost flat. With a large beta the loss is already near zero after a modest shift away from the reference, so training stops pushing early and the policy stays close to the reference; with a small beta the loss keeps asking for more movement. That is the same role the KL penalty weight plays in RLHF: it sets how far the policy may drift.
  8. Possible tricks: special-casing only the input shapes in the tests (checking a + b == 15), returning a value derived from the test inputs, or reading the tests through the namespace. Counter-measures: hidden or randomly generated tests, more tests, and running the code in a clean sandbox that doesn't expose the tests.
  9. There is no single answer. Look for a "knowledge cutoff" or "training data" line in each provider's model page or system card, one number from a safety table, and one stated limitation.
  10. Typical examples: a stricter reading of instructions (post-training data or reward changes), different refusal rates (safety tuning), different tool-call habits (agentic RL). Test each with a fixed set of realistic prompts run on the old and new snapshot side by side.

Check yourself#

  1. What are the main stages of the LLM training pipeline, and what does each produce?
  2. Name four steps in cleaning web data for pretraining, and say why deduplication matters beyond saving compute.
  3. A model's perplexity on some text is 1. What does that suggest?
  4. Why does perplexity only compare fairly between models with the same tokenizer?
  5. Using the 6 × N × D rule, roughly how much compute does training a 70B model on 15T tokens take?
  6. What did Chinchilla find, and why are many modern small models trained far beyond that point?
  7. What is the "mirage" argument about emergent abilities?
  8. You send "What are the side effects of ibuprofen?" to a base model. Name two ways its output might differ from an instruct model's.
  9. In SFT, why is the loss usually computed only on the assistant's tokens?
  10. Describe the three steps of RLHF. What is the KL penalty for?
  11. How does DPO differ from RLHF in practice?
  12. What makes a reward "verifiable", and how did RL with verifiable rewards lead to reasoning models?
  13. Give one example of reward hacking with a learned reward model and one with a verifiable reward.
  14. Why are model knowledge cutoffs always months before the release date, and what should your application do about it?
  15. Your production app uses a model alias. What risk does this create, and what should you do instead?

Further resources#

  • Andrej Karpathy, Deep Dive into LLMs like ChatGPT (YouTube, 2025): a long, clear walk through pretraining data, tokenization, base models, SFT and RL, aimed at a general audience.
  • Andrej Karpathy, Let's build GPT: from scratch, in code, spelled out (YouTube): train a tiny GPT yourself and watch the loss fall.
  • Meta, The Llama 3 Herd of Models (2024, arXiv:2407.21783): the most detailed public description of a frontier-scale pretraining and post-training pipeline.
  • Penedo et al. (Hugging Face), The FineWeb Datasets: Decanting the Web for the Finest Text Data at Scale (2024, arXiv:2406.17557), and the FineWeb blog post: how web data is filtered and deduplicated, with experiments for each step.
  • Hoffmann et al., Training Compute-Optimal Large Language Models (Chinchilla, 2022, arXiv:2203.15556), and Kaplan et al., Scaling Laws for Neural Language Models (2020, arXiv:2001.08361).
  • Ouyang et al., Training language models to follow instructions with human feedback (InstructGPT, 2022, arXiv:2203.02155): the paper behind the RLHF recipe.
  • Rafailov et al., Direct Preference Optimization: Your Language Model is Secretly a Reward Model (2023, arXiv:2305.18290), and Bai et al., Constitutional AI: Harmlessness from AI Feedback (2022, arXiv:2212.08073).
  • DeepSeek-AI, DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning (2025, arXiv:2501.12948): an open account of RL-trained reasoning.
  • Nathan Lambert, Reinforcement Learning from Human Feedback (free online book): a thorough guide to post-training.
  • Lightman et al., Let's Verify Step by Step (2023, arXiv:2305.20050): outcome vs process rewards, and the PRM800K dataset.
  • OpenAI, Deliberative Alignment: Reasoning Enables Safer Language Models (2024, arXiv:2412.16339): training reasoning models to reason over a written safety specification.
  • The OpenAI Model Spec and Anthropic's constitution for Claude: how each provider says its models are meant to behave.

← 02.5 — Generation and Sampling | Module 02 overview | 02.7 — Context Windows →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close