Pretraining, Scaling Laws, and Compute

Session 2: Lecture + live-coding lab

Lambert Fatoux

Learning outcomes (today)

  1. Write the causal-LM objective as next-token maximum likelihood and compute its loss by hand
  2. Explain why tokenisation is an economic decision, and run BPE merge by merge
  3. Use C ≈ 6ND to turn a model and a dataset into FLOPs, GPU-hours and euros
  4. Apply the Chinchilla rule (≈ 20 tokens per parameter) to size a model, and know when to break it

Produced: a BPE tokeniser trained on WikiText + a compute-optimal sizing estimate

Warm-up quiz 1/4: the causal mask

In a decoder-only transformer, what does the causal mask do?

A Removes the padding tokens from the batch

B Sets the scores of future positions to −∞ before the softmax

C Sets the attention weights of future positions to 0 after the softmax

D Hides a random 15% of the tokens, which the model must guess

✅ Answer: B

After the softmax (C), the rows of weights no longer sum to 1. D is how BERT-style encoders are trained, with no causal mask.

Warm-up quiz 2/4: why √d_k?

Attention computes \(\mathrm{softmax}(QK^\top / \sqrt{d_k})\,V\). Why divide by \(\sqrt{d_k}\)?

A To make the cost of attention linear in T

B Dot products grow with d_k: unscaled, the softmax puts almost all the weight on one token

C So that each row of weights sums to 1

D To divide d_model evenly between the heads

✅ Answer: B

The softmax already makes rows sum to 1 (C). The scores are still (B, T, T): attention stays quadratic in T (A).

Warm-up quiz 3/4: the LM head

The model reads token IDs of shape (B, T). What shape does the LM head output?

A (B, d_model)

B (B, T, d_model)

C (B, T, V)

D (B, V)

✅ Answer: C

One score per vocabulary token, at every position. (B, T, d_model) is the output of the decoder blocks, before the LM head. Today the loss uses all B × T positions.

Warm-up quiz 4/4: encoder or decoder?

Session 1’s lab model was distilbert-base-uncased. Which statement is true?

A It is decoder-only, like GPT, and generates text

B It is an encoder: good for embeddings, it cannot generate text

C It is an encoder-decoder built for translation

D Its causal mask lets it read the whole sentence at once

✅ Answer: B

Same building blocks in the three families: the mask decides. An encoder sees both sides of each token, so it has no next-token objective. Today we pretrain a decoder.

Recap: what we built in Session 1

  • A decoder block maps (B, T, d_model) → (B, T, d_model); the LM head maps to (B, T, V)
  • Session 1 wrote this width C; from today on it is d_model, because C will mean compute
  • The causal mask forbids looking at the future

Questions we’ll answer today

Three questions Session 1 left open:

  • Where do the weights come from? → pretraining
  • Where do the token IDs (and V, T) come from? → tokenisation
  • How big should the model be, and how much data does it need? → scaling laws

Notation for today

Tokens V: vocabulary size (GPT-2: 50,257) T: context length, tokens per sequence (GPT-2: 1,024)

Model d_model: size of each token vector (GPT-2 small: 768) N: number of parameters (GPT-2 small: 124M)

Budget D: training tokens, all epochs counted C: training compute in FLOPs, C ≈ 6ND

⚠️ Session 1’s C (channels) is today’s d_model: today C always means compute.

Pretraining

The life of an LLM

What “pretraining” really means

  • A randomly initialised transformer (Session 1) predicts the next token at every position of trillions of tokens; gradient descent corrects it, for weeks
  • The result is a base model: a superb document completer, not yet an assistant

The base model learnt that quiz questions often come in lists. Turning it into an assistant is post-training (Session 3).

Self-supervision: the trick that unlocked scale

  • Classic supervised ML needs labels: expensive, slow, human
  • Next-token prediction needs no annotation: the text is the label
"The capital of France is Paris."
 → (The → capital), (The capital → of), ..., (... is → Paris), (... Paris → .)
  • Every sentence on the web = several free training examples
  • To predict well, the model must implicitly learn grammar, facts, style, code, some reasoning…

💼 Business corner

Labelled datasets are bounded by annotation budgets (ImageNet ≈ 1.2M labelled images). Self-supervised text corpora are bounded only by how much text exists: that difference is why language models scaled first.

Where does the data come from?

Web crawl Common Crawl, FineWeb: volume and diversity

Encyclopaedic Wikipedia: clean, factual, multilingual

Books Public-domain books: long-range coherence

Code GitHub (permissive licences): code, and structured reasoning

Scientific arXiv, PubMed: maths and technical vocabulary

Synthetic Text generated by other LLMs: targeted skills, “textbook” quality

Typical recipe: mostly web, upsampled with high-quality sources.

The data pipeline

Data quality > data quantity

Deduplicate In the C4 dataset, one 61-word sentence appears 60,000+ times. Duplicates waste compute and boost memorisation.

Filter FineWeb-Edu keeps the pages a classifier rates “educational”: 1.3T tokens that beat much larger unfiltered sets on knowledge benchmarks.

Synthesise Microsoft’s phi-1 (1.3B parameters, 2023), trained on “textbook-quality” data, matched much bigger code models.

💼 Business corner

The architecture is mostly public; the data recipe is what labs keep secret.

The causal-LM objective

From a sentence to a probability

A language model assigns a probability to any token sequence \(x_1, \dots, x_T\).

The chain rule of probability (exact, no assumption) splits it into next-token predictions:

\[ P(x_1, \dots, x_T) = \prod_{t=1}^{T} P(x_t \mid x_1, \dots, x_{t-1}) \]

P("the cat sat") = P(the) × P(cat | the) × P(sat | the cat)
  • The transformer outputs exactly these conditional distributions, one per position
  • The causal mask (Session 1) guarantees position t only sees \(x_{<t}\)

Maximum likelihood → cross-entropy

Training = find weights \(\theta\) that make the real text as probable as possible:

\[ \max_\theta \prod_{t} P_\theta(x_t \mid x_{<t}) \quad\Longleftrightarrow\quad \min_\theta \; \text{loss}(\theta) = -\frac{1}{T}\sum_{t=1}^{T} \ln P_\theta(x_t \mid x_{<t}) \]

  • Product → sum of logs: numerically stable, easy to differentiate
  • Minus sign: we minimise a loss; ln is the natural log
  • This is exactly the cross-entropy between the true next token (one-hot) and the predicted distribution
  • Example: a sequence of 7 predictions → loss = mean of the 7 values −ln p(true token)

Training pairs: shift by one

What the loss rewards

The loss explodes when the model is confidently wrong: it learns to hedge when unsure.

Tiny numerical example

PyTorch causal-LM loss

import torch.nn.functional as F

def causal_lm_loss(model: torch.nn.Module,
                   batch: torch.Tensor,
                   pad_id: int) -> torch.Tensor:
    """batch: (B, T+1) token IDs, right-padded with pad_id."""
    inputs = batch[:, :-1]             # (B, T)  tokens 0 to T-1
    targets = batch[:, 1:]             # (B, T)  tokens 1 to T
    logits = model(inputs)             # (B, T, V)
    return F.cross_entropy(
        logits.flatten(0, 1),          # (B*T, V)
        targets.flatten(),             # (B*T,)
        ignore_index=pad_id,           # padding is not language
    )
  • B = batch size, the number of sequences per training step
  • Then the usual step: loss.backward(), optimizer.step()

One forward pass, B × T predictions

  • The B × T predictions are trained in parallel, from one forward pass
  • Unlike models that read one token at a time, this parallelism is why transformers scale

Perplexity: loss you can explain to a manager

\[ \text{perplexity}(\theta) = e^{\,\text{loss}(\theta)} \]

  • The model is as uncertain as if it chose uniformly among ppl tokens
  • Before training, the model spreads its probability evenly over the V tokens: p = 1/V, so loss = −ln(1/V) = ln V and ppl = V
    • GPT-2 (V = 50,257): initial loss ≈ 10.8, perplexity ≈ 50,000
  • A GPT-2-small reproduction (nanoGPT) reaches ≈ 2.85 validation loss → ppl ≈ 17

⚠️ Losses and perplexities are only comparable with the same tokeniser and the same evaluation text.

Training vs held-out loss

Signal Measures Watch for
Training loss Fit to text already seen Goes down almost always
Validation loss Prediction on held-out text The number you report
Gap between them Memorisation Overfitting, duplicated data
  • Large pretraining runs see each token ~once → they rarely overfit; the gap stays small
  • Small models trained for many epochs on a small corpus (your lab!) do overfit

Course doctrine applies: a loss is only meaningful on a held-out set.

Fun fact: prediction is compression

🎲 Fun fact

A model that predicts the next symbol well can be turned into a lossless compressor (arithmetic coding): each token costs −log₂ p bits.

DeepMind (2023) showed that Chinchilla-70B, trained only on text, compresses ImageNet patches to 43% of their size (PNG: 58%) and LibriSpeech audio to 16% (FLAC: 30%).

  • Lower cross-entropy = fewer bits per token = better compression
  • This is why researchers report bits-per-byte: it is independent of the tokeniser
  • Bits-per-byte = total bits (sum of −log₂ p over all tokens) / number of UTF-8 bytes of the text

Tokenisation

Why tokenisation matters

The tokeniser decides what one prediction step is. It sets:

  • Vocabulary size V: Embedding + LM-head parameters (V × d_model each) and softmax cost
  • Tokens per document T: Attention cost (T²), context-window usage, latency
  • Token count: Your API bill and the D in scaling laws
  • What a “unit” is: Spelling, arithmetic, multilingual ability

A tokeniser is trained once, before the model, and frozen. Changing it means retraining the model.

Three granularities

Subwords: the best of both worlds

  • Frequent words stay whole: " the", " Paris", " because"
  • Rare words split into reusable pieces: "un" + "believ" + "ably"
  • Unseen words can always be built from smaller pieces → no <unk>
  • Morphology is (partly) captured for free: normal, normal ly, normal ity

Rule of thumb for English with modern tokenisers:

1 token ≈ 4 characters ≈ 0.75 words      →   1,000 words ≈ 1,300 tokens

How many tokens is a book?

English, ×1.33 tokens per word. Word counts are approximate and vary by edition.

💼 Business corner

At $3 per million input tokens, having a model read Philosopher’s Stone costs about $0.30. Rereading it on every request in a chat is how bills grow.

Byte-Pair Encoding (BPE) in one sentence

Start from single symbols, then repeatedly merge the most frequent adjacent pair into a new symbol, until the vocabulary reaches the target size.

  • Invented in 1994 as a data-compression algorithm, adapted to neural machine translation in 2016
  • Used by GPT-2 → GPT-5, Llama 3, Mistral, Qwen, DeepSeek…

Two phases:

  1. Training (once, on a corpus): learn an ordered list of merges
  2. Encoding (every request): apply the merges, in order, to new text

Counting pairs: merge 1 in detail

Toy corpus (word → count): cat ×8, cats ×4, hat ×5, that ×6, chat ×3

Count each adjacent pair, weighted by word frequency:

a t = 26cat 8 + cats 4 + hat 5 + that 6 + chat 3
h a = 14hat 5 + that 6 + chat 3
c a = 12cat 8 + cats 4
t h = 6that 6
t s = 4cats 4
c h = 3chat 3

Winner: a t → at. Add at to the vocabulary, rewrite the corpus, recount, repeat.

BPE training, step by step

BPE training in 15 lines

def train_bpe(word_counts: dict[str, int],
              n_merges: int) -> list[tuple[str, str]]:
    words = {tuple(w): c for w, c in word_counts.items()}
    merges = []
    for _ in range(n_merges):
        pairs = count_pairs(words)           # weighted pair counts
        if not pairs:
            break
        best = pairs.most_common(1)[0][0]    # the most frequent pair
        merges.append(best)
        words = {merge(s, best): c for s, c in words.items()}
    return merges

toy = {"cat": 8, "cats": 4, "hat": 5, "that": 6, "chat": 3}
print(train_bpe(toy, n_merges=4))
[('a', 't'), ('h', 'at'), ('c', 'at'), ('t', 'hat')]

count_pairs and merge (replace a pair by the joined symbol) are provided in the lab.

Production details

Byte-level GPT-2 onwards: start from the 256 bytes, not characters. Any string (emoji, Chinese, binary junk) is encodable, no <unk> ever.

Pre-tokenisation A regex first splits on spaces, punctuation and digits, so merges never cross word boundaries.

Spaces belong to tokens " Paris" ≠ "Paris". GPT-2 displays the space as Ġ, SentencePiece as ▁.

Special tokens Added by hand: <|endoftext|>, <pad>, later chat markers like <|im_start|>.

>>> tok.tokenize("Hello world! Paris")        # GPT-2 tokeniser
['Hello', 'Ġworld', '!', 'ĠParis']

BPE and its cousins

BPE Merge the most frequent pair, bottom-up. Used by: GPT family, Llama 3, Mistral, Qwen

WordPiece Same loop, a different score for the pair (next slide). Used by: BERT, DistilBERT (Session 1 lab)

Unigram LM Start from a huge vocabulary, prune the tokens that matter least, top-down. Used by: T5, ALBERT

SentencePiece is a library, not a fourth algorithm: it treats text as a raw stream (space = ▁) and runs BPE or Unigram. Used by Llama 1 and 2, Gemma, T5.

All produce the same object: a vocabulary + rules to map text ↔︎ integer IDs.

WordPiece: same loop, different score

  • Dividing by the parts’ counts favours pairs that almost always appear together, not just frequent ones
  • At encoding time, WordPiece takes the longest vocabulary match from the left: unaffable → un ##aff ##able

Vocabulary size is a design trade-off

Model Vocabulary V
GPT-2 (2019) 50,257
Llama 2 (2023) 32,000
GPT-4 (cl100k) ~100,000
Llama 3 (2024) 128,256
GPT-4o (o200k) ~200,000
Gemma (2024) ~256,000
  • Bigger V → shorter sequences (cheaper attention, more text per context window), better multilingual coverage
  • Bigger V → bigger embedding matrix & LM head, rarer tokens seen fewer times in training
  • Llama 3 8B: 128,256 × 4,096 ≈ 525M parameters per embedding matrix (input + output ≈ 13% of the model)

Tokens are the currency of LLMs

💼 Business corner

  • APIs bill per million tokens, input and output priced separately
  • Context windows (“1M tokens”) and rate limits are counted in tokens
  • Latency ≈ time-to-first-token + output tokens / tokens-per-second

The token tax. A tokeniser trained mostly on English splits other languages into more pieces:

  • The same text can need up to ~15× more tokens than in English → higher cost and latency, less content per context window
  • Larger, more multilingual vocabularies (o200k, Gemma) are partly a market-expansion decision

When the tokeniser acts weird

🎲 Fun facts

  • “How many r’s in strawberry?” GPT-2 sees st raw berry: it never sees letters, so counting them is surprisingly hard
  • Arithmetic: GPT-2 splits "12345" into 123 45. Digit grouping changes from one tokeniser to the next, so modern tokenisers split numbers into fixed chunks of 1 to 3 digits
  • Glitch tokens: " SolidGoldMagikarp" (a Reddit username) got its own GPT-2/3 token, but almost never appeared in training. Asking GPT-3 to repeat it produced nonsense or evasions

Measuring a tokeniser

In the lab, on the validation split (never on the training text):

Round trip decode(encode(s)) == s for English, French with an emoji, and Python code. Byte-level BPE never loses a character.

Tokens per 1,000 characters For V = 1k, 8k and 32k. Fewer tokens = shorter sequences for the same text, but a bigger embedding matrix (V × d_model).

A tokeniser trained on Wikipedia and evaluated on Wikipedia looks great. Try it on tweets, code or French and see what happens.

Scaling laws

The bitter lesson

“The biggest lesson that can be read from 70 years of AI research is that general methods that leverage computation are ultimately the most effective.” (R. Sutton, 2019)

  • GPT-1 (2018): 117M parameters; GPT-2 (2019): 1.5B; GPT-3 (2020): 175B
  • Each jump: same recipe (transformer + next-token loss), more parameters, more data, more compute

The question for a lab with a fixed budget:

I have C FLOPs. How should I split them between a bigger model (N) and more data (D)?

Where does the 6 come from?

One approximation links the three budgets: C ≈ 6ND, with C in FLOPs (floating-point operations)

  • Inference only needs the forward pass: ≈ 2N FLOPs per generated token

In the scaling-law papers, N counts the non-embedding parameters.

Reading a scaling plot

  • Each model size eventually plateaus: it cannot absorb more data
  • The best loss for a budget moves to bigger models as C grows; it bends because no model goes below an irreducible loss (the entropy of text)

Chinchilla (DeepMind, 2022)

DeepMind trained 400+ models (70M → 16B parameters, 5B → 500B tokens) and asked: for a fixed C, which N gives the lowest loss?

The Chinchilla result

Compute-optimal training scales N and D equally:

\[ N_{\text{opt}} \propto C^{0.5} \qquad D_{\text{opt}} \propto C^{0.5} \qquad\Rightarrow\qquad \boxed{D_{\text{opt}} \approx 20 \, N} \]

The proof by example, same compute budget (≈ 5.8 × 10²³ FLOPs):

Model N D tokens/param MMLU
Gopher 280B 300B 1.1 60.0%
Chinchilla 70B 1.4T 20 67.6%

4× smaller, better on almost every benchmark, and 4× cheaper to serve.

From the rule to a recipe

Combine \(C = 6ND\) and \(D = 20N\):

\[ C = 6 \cdot N \cdot 20N = 120\,N^2 \]

\[ \Rightarrow\qquad N_{\text{opt}} = \sqrt{C / 120}, \qquad D_{\text{opt}} = 20\,N_{\text{opt}} \]

Budget C \(N_{\text{opt}}\) \(D_{\text{opt}}\)
10¹⁹ FLOPs 290M 5.8B tokens
10²¹ FLOPs 2.9B 58B tokens
5.8 × 10²³ (Gopher’s budget) 69B 1.4T tokens ← Chinchilla!

Three ways to use the rule

  • MFU (model FLOPs utilisation): the share of the GPU’s peak FLOP/s a run actually achieves (40% here)
  • Units: tokens (of your tokeniser), not words, not documents, not bytes

Compute, hardware and money

From FLOPs to GPU-hours

\[ \text{time} \approx \frac{C}{\text{#GPUs} \times \text{peak FLOP/s} \times \text{MFU}} \]

  • Peak (BF16, dense): A100 ≈ 312 TFLOP/s, H100 ≈ 989 TFLOP/s, B200 ≈ 2.3 PFLOP/s
  • MFU (model FLOPs utilisation): the share of peak you actually achieve: 30 to 50% for good large-scale runs (communication, memory bandwidth, data loading, failures)

Example, 125M model on 2.5B tokens:

C = 6 × 1.25×10⁸ × 2.5×10⁹ ≈ 1.9×10¹⁸ FLOPs
one A100 at 40% MFU ≈ 1.25×10¹⁴ FLOP/s  →  1.5×10⁴ s ≈ 4 hours

A real frontier run: Llama 3.1 405B

Quantity Value (reported by Meta, 2024)
N 405B parameters
D 15.6T tokens (≈ 38 tokens/param)
6ND 6 × 4.05×10¹¹ × 1.56×10¹³ ≈ 3.8 × 10²⁵ FLOPs ✓
Hardware up to 16,384 H100 GPUs
GPU-hours ≈ 30.8M H100-hours → ≈ 80 days on 16k GPUs
Implied MFU 3.8×10²⁵ / (30.8M × 3,600 s × 989 TFLOP/s) ≈ 35%

💼 Business corner

At ~US$2 per H100-hour, that is ≈ US$60M of compute for the final run alone, before failed experiments, ablations, data, salaries and post-training. Sam Altman said GPT-4 cost “more than $100M”.

From $48 to $730B: what LLMs cost

Orders of magnitude, not invoices.

Cheaper and dearer at the same time

A fixed capability gets cheaper fast

  • GPT-2 (2019): ≈ $43,000 to train
  • Same level in 2025 (nanochat, one 8×H100 node, ~2 h): ≈ $48
  • → ~600 to 900× cheaper in 6 years: better GPUs, code and data
  • Being second, a year later with open recipes, costs a fraction of being first

The frontier gets more expensive

  • Final-run cost of frontier models: ×2.4 per year since 2016 (Epoch AI)
  • GPT-4 ≈ $100M (2023) → Grok 4 ≈ $490M (2025)
  • Projected: > $1B for a single run by 2027

🎲 Fun fact

GPT-3’s training was estimated at ≈ 1,300 MWh and ≈ 550 t CO₂e: roughly the yearly electricity use of 120 US homes.

Where the money goes

Full development cost of GPT-4 and Gemini Ultra (Epoch AI estimate):

  • Hardware (GPUs or TPUs, servers, network): 47 to 67%
  • R&D staff: 29 to 49%
  • Energy: 2 to 6%
  • Rent vs own: cloud prices ≈ 2× the amortised cost of owned hardware. Llama 3.1 405B: ~$60M at $2/H100-hour (our estimate) vs ~$170M (AI Index)
  • Headline numbers cover the final run only: no failed runs, ablations, data, salaries, post-training or serving

Compute is not the only constraint: memory

  • Plus activations, which grow with batch size × sequence length × layers
  • Hence sharding across GPUs (ZeRO / FSDP), activation checkpointing, etc.
  • A plan can fit the FLOPs budget and still not fit in memory

Beyond Chinchilla

Chinchilla optimises the wrong bill (for products)

Chinchilla minimises training compute. But a product pays, with S = tokens served:

\[ \text{total FLOPs} \approx \underbrace{6ND}_{\text{train once}} + \underbrace{2NS}_{\text{serve forever}} \]

Example: S = 1T tokens per day 70B on 1.4T tokens 8B on 15T tokens
Training, 6ND 5.9 × 10²³ FLOPs 7.2 × 10²³ FLOPs
Serving, 2NS per day 1.4 × 10²³ FLOPs 1.6 × 10²² FLOPs
Serving costs more than training after 4 days 45 days
  • Over one year, the 8B model costs about 8× fewer FLOPs in total
  • Loss keeps improving (slowly) past 20 tokens/param: it does not plateau there

Modern models are “over-trained” on purpose

* DeepSeek-V3 is a Mixture-of-Experts (MoE) model: each token goes through only a few of many expert sub-networks, so 671B total but 37B active parameters per token (used here).

Llama 3 8B: a case study

  • Training compute: 6 × 8×10⁹ × 15×10¹² ≈ 7×10²³ FLOPs
  • Chinchilla-optimal for that budget: N ≈ √(7×10²³ / 120) ≈ 77B parameters
  • Meta chose 8B (10× smaller) and reported that the loss was still improving log-linearly at 15T tokens

💼 Business corner

An 8B model runs on a single consumer GPU or a laptop (quantised), costs ~10× less per token than a 77B one, and answers faster. For on-device assistants (Apple’s ~3B on-device model, Gemini Nano), phones, or high-volume APIs, inference-optimal beats training-optimal.

Mixture-of-Experts: bending the rule

  • Replace each MLP by many expert MLPs + a router that picks a few experts per token
  • Total parameters (capacity, memory) ≫ active parameters (compute per token)
Model Total Active per token
Mixtral 8×7B (Mistral, 2023) 47B 13B
DeepSeek-V3 (2024) 671B 37B
  • Compute laws use active N; memory and serving hardware depend on total N
  • DeepSeek-V3 reported 2.8M H800-hours (≈ US$5.6M) for its final run, a headline that shook Nvidia’s stock in January 2025 (it excludes research and earlier runs)

The data wall

  • Llama 3: 15T tokens; Qwen3: 36T tokens; Qwen3-0.6B: 60,000 tokens per parameter
  • Epoch AI estimates the stock of quality public human text at ~300T tokens, likely fully used between 2026 and 2032

What labs do about it:

Repeat data Up to ~4 epochs is almost as good as fresh data; beyond that, returns fade fast.

Synthetic data Generate textbooks, maths problems and code with existing models, then filter hard.

New modalities Video, audio and images contain far more raw information than text.

Licensed data deals News publishers, forums (Reddit), stock-photo libraries: data has become a traded asset.

Should your company pretrain?

  • Prompting an API (€ per call): almost always the first step
  • RAG over your documents (S5, € + engineering): knowledge that changes, citations needed
  • Fine-tuning / LoRA (S3, €1k to €100k): style, format, narrow tasks
  • Continued pretraining (€100k to €1M+): large proprietary corpus, new language or domain jargon
  • Pretraining from scratch (€10M+): sovereignty, a new language family, or you are a model company

💼 Cautionary tale

BloombergGPT (2023): 50B parameters, ~570B tokens of which half proprietary financial data, ≈ 1.3M A100-hours. Within months, general-purpose GPT-4 matched or beat it on many financial NLP tasks. Who pretrains successfully at scale: frontier labs, and sovereign/open efforts like Mistral (France), Apertus (Switzerland, 2025), Qwen and DeepSeek (China).

Practice session

Lab overview

Stack: Python, torch, tokenizers, datasets, transformers (CPU is enough).

  1. The causal-LM objective: loss, perplexity, shift by one, the ln V check (a first loss far from ln V means a bug)
  2. BPE from scratch on the toy corpus: reproduce the merges of the slides
  3. Byte-level BPE on WikiText: train, check the round trip, count tokens per 1,000 characters for V = 1k, 8k, 32k
  4. Sizing worksheet: FLOPs, GPU-hours, euros

Given: merge, count_pairs, the tokeniser pipeline, three trained tokenisers in artifacts/. You write: eight blanks (____), one line each.

Lab part 2: BPE from scratch

  • merge and count_pairs are provided; in train_bpe, write one line: pick the most frequent pair
  • Run it on {"cat": 8, "cats": 4, "hat": 5, "that": 6, "chat": 3}
  • Check: your first 4 merges are a t, h at, c at, t hat

Then write the encoder:

def encode_word(word: str, merges: list[tuple[str, str]]) -> list[str]:
    symbols = tuple(word)
    for pair in merges:                 # apply merges in learned order
        symbols = merge(symbols, pair)
    return list(symbols)

encode_word("chats", toy_merges)   # expected: ['c', 'hat', 's']

Lab part 3: train on WikiText

wikitext = datasets.load_dataset("Salesforce/wikitext",
                                 "wikitext-103-raw-v1")
TRAIN_SLICE = 50_000    # rows of the train split: stays fast on CPU
train_texts = [t for t in wikitext["train"].select(range(TRAIN_SLICE))["text"]
               if t.strip()]
valid_texts = [t for t in wikitext["validation"]["text"] if t.strip()]

In train_bpe_tokenizer, the tokeniser, pre-tokeniser, decoder and trainer are built. Your one line:

tok.train_from_iterator(batch_iterator(texts), trainer=trainer,
                        length=len(texts))

The three tokenisers (V = 1k, 8k, 32k, trained on 200,000 rows) load from artifacts/. Set LOAD_PRECOMPUTED = False to train them yourself.

Lab part 3: measure on held-out text

assert tok.decode(tok.encode(s).ids) == s       # round trip

sample = "".join(valid_texts[:2_000])           # validation split only
for vocab_size, tok in our_tokenizers.items():
    n_tokens = len(tok.encode(sample).ids)
    print(f"V = {vocab_size:>6,}: "
          f"{1000 * n_tokens / len(sample):6.1f} tokens per 1,000 characters")
  1. Round trip on English, French with an emoji, and Python code
  2. Tokens per 1,000 characters for V = 1k, 8k, 32k
  3. Choose a vocabulary size for a small model, in one sentence; the 8k one is saved to artifacts/wikitext-bpe-chosen.json for Part 4

Lab part 4: sizing worksheet

  1. Toolkit: complete compute_optimal, \(N_{\text{opt}} = \sqrt{C / (6 \times 20)}\); the check cell reproduces the worked examples of the slides
  2. Data-constrained: count the WikiText-103 train tokens with your tokeniser (10% of the rows, scaled up), then write N = tokens / 20
  3. The bill: €2 per A100-hour, €2.50 per H100-hour. Write the cost of a Chinchilla 7B on 1,000 H100: hours × GPUs × price
  4. Question: why does a real 7B model cost much more than this number?

Knowledge check

  1. Why is the target sequence the input shifted by one, and why can a single forward pass train T predictions?
  2. A model gives probability 0.05 to the correct token. What is its loss? Its perplexity if every token looked like this?
  3. Why can’t you compare the loss of two models using different tokenisers?
  4. How many tokens does a Chinchilla-optimal 1B model need? How many FLOPs?
  5. Give two business reasons to train a model well beyond 20 tokens per parameter.

Key takeaways

  • Pretraining = next-token prediction on trillions of tokens, optimised with cross-entropy on shifted targets
  • Self-supervision is what made scale possible: the text is its own label
  • The tokeniser fixes V, T and the token count: it shapes cost, latency, multilingual fairness and even what the model can “see”
  • BPE greedily merges frequent pairs; byte-level BPE never needs <unk>
  • C ≈ 6ND; loss follows power laws in N, D and C
  • Chinchilla: ≈ 20 tokens per parameter is training-optimal; products deliberately over-train smaller models for cheaper inference

Checklist (close)

Before you leave, you can explain:

Next session

Session 3 (SFT, RLHF and DPO): from a base model that completes documents to an assistant that follows instructions.

  • Supervised fine-tuning, reward models, PPO vs DPO
  • LoRA: fine-tune a 1B model on a laptop-scale budget

Bring your tokeniser and sizing worksheet: we will compare post-training compute with what you computed today.