Session S18

LLM Pretraining

A decoder-only model is trained only to predict the next token. Why is that objective enough, which text does it learn from, what does training it cost, how should a fixed compute budget be split between parameters and data, and which claims about what scale buys hold up?

Deep Learning · CS 4715/5715 · University of Idaho

HW2 is due today, and HW3 goes out today

Before the material, three course items: HW2, HW3, the project.

  • HW2 (CNNs and transfer learning) is due today at 11:59 PM Pacific; the 12-hour grace period applies.
  • HW3 (Transformer from scratch) goes out today and is due the Monday after next (S22). You build a decoder-only language model from its parts: attention, the causal mask, multi-head attention, the pre-norm block, and a tiny model that you train and sample from.
  • HW3's train_step is today's training step in miniature: a causal mask and cross-entropy at every position, on a toy task (predict the previous token).
  • Project: the proposal is due at the end of the week after next (the S23 week); build it on your pre-proposal feedback.

S17 built a decoder-only Transformer that predicts at every position

Today trains the model S17 assembled. For a batch of \(B\) sequences of \(T\) token ids, with a vocabulary of \(V\) entries:

ids(B, T)embeddingtable V × d_model+ positionspre-norm blockscausal maskfinal LNlinear headd_model × Vlogits(B, T, V)(B, T, d_model)(B, T, d_model)(B, T, d_model)(B, T, d_model)(B, T, V)
  • The causal mask: \(-\infty\) above the diagonal, before the softmax, gives later keys weight exactly 0; S17's test agrees (edit token 5: positions 0–4 change by exactly 0).
  • So one pass over \(T\) tokens gives \(T\) next-token examples, each from its own past only.
  • Decoder-only (the GPT line): this stack trained on next-token prediction, which learns from every position and scaled. Next-token prediction needs no labels.

S17 built the model; today trains it.

Today follows one objective through its text, cost, budget and claims

Five parts, each answering one clause of the title page's question; a sixth closes.

partthe question it answers
1 · One objectivewhy is predicting the next token enough? The loss with its shapes; labels taken from the text
2 · Datawhich text does it learn from? The pipeline from a web crawl to a training mixture; finding duplicates
3 · Computewhat does training cost? A count of operations per parameter and token, checked layer by layer, turned into days
4 · Scaling lawshow should a fixed budget be split between parameters and data? Two published answers (2020, 2022), why they differ, a toy run
5 · Emergencewhich claims about what scale buys hold up? Sudden abilities, or the metric
6 · Closefive common mistakes, today's answer, next time

Each of Parts 1–5 ends on a self-check. First, the objective.

The objective is the average \(-\log p\) of every next token

Part 1 · One objective. Pretraining minimizes one number (reading 3.5):

\[L=-\frac{1}{T}\sum_{t}\log p\big(x_t\mid x_{1..t-1}\big)\]
LTBTBTBTBVVmodel(x)softmax overthe last axis−log p of thetrue next tokenmean overall B·T(B, T)a batch oftoken sequences(B, T, V)a score for every vocabularyentry, at every position(B, T, V)p(· | prefix) at every position;each row sums to 1 (framed)(B, T)one lossper positionscalar

Here \(\log\) is the natural log, as in PyTorch; another base only rescales \(L\) by a constant. This is S03's cross-entropy, averaged like S08's CrossEntropyLoss.

Each target is simply the next token (S17's shift by one). The next page computes this loss on a six-token sentence.

With targets shifted by one, six tokens give five predictions

Random logits stand in for model(x); the loss arithmetic is the same:


import torch
import torch.nn.functional as F
torch.manual_seed(0)
ids = torch.tensor([[7, 2, 5, 9, 7, 4]])   # the cat sat on the mat
x, y = ids[:, :-1], ids[:, 1:]             # inputs, targets: (1, 5) each
logits = torch.randn(1, 5, 10)             # stands in for model(x): (B, T, V)
logp = F.log_softmax(logits, dim=-1)       # log p over the V = 10 entries
per_pos = -logp[0, torch.arange(5), y[0]]  # at t: -log p of target y[0, t]
loss = F.cross_entropy(logits.view(-1, 10), y.view(-1))  # (B*T, V), (B*T,)
print(x.tolist(), y.tolist())
print([round(v, 4) for v in per_pos.tolist()])
print(f"mean {per_pos.mean().item():.4f}, cross_entropy {loss.item():.4f}")
  
t0the7cat22.43821cat2sat52.99492sat5on91.53763on9the72.91854the7mat45.3478x = ids[:, :-1]y = ids[:, 1:]is scored on−log pof the targetmean 3.0474 = cross_entropy 3.0474The values are the three prints above.
  • view(-1, 10), view(-1): logits as (B*T, V), targets as (B*T,), as F.cross_entropy (S08's CrossEntropyLoss as a function) expects.

Self-supervised means the text supplies every label; the step is S08's

No person wrote the previous page's targets: they are the text itself, shifted by one.

  • Self-supervised: no labeled dataset, no annotation, no task-specific head. Every position of every document is a prediction problem: a trillion-token corpus supplies about a trillion of them.
  • The step is S08's loop, plus S17's causal mask (inside model) and a loss at every position. Reading 3.5's toy script, with its get_batch:

# excerpt of reading 3.5's toy script; len(chars) is V, opt is AdamW (S08)
def get_batch(split_data, batch_size, gen):  # CTX: the context length T
    ix = torch.randint(0, len(split_data) - CTX - 1, (batch_size,), generator=gen)
    x = torch.stack([split_data[i:i + CTX] for i in ix])
    y = torch.stack([split_data[i + 1:i + CTX + 1] for i in ix])  # y: x shifted by one
    return x, y
x, y = get_batch(train_data, batch_size, gen)
loss = F.cross_entropy(model(x).view(-1, len(chars)), y.view(-1))
opt.zero_grad(); loss.backward(); opt.step()
  

One loss, and no task in it. Why should that produce anything useful?

One plain objective is enough because predicting well needs what the text depends on

Reading 3.5's informal argument: the loss is lowest when the model's probabilities match how text actually continues. Text continues according to facts, grammar, code and arguments, so lowering the loss forces the model to represent them; the objective needs nothing else.

to predict the next …the model needs
word of "the capital of Idaho is"a fact
line of a Python functionthe code above it
closing argument of an essaythe argument so far

A lower loss means the model has learned more of what the text depends on. What does the objective reward, and what does it not guarantee?

What the objective rewards, and what pretraining delivered from 2018 on

The argument is informal; what the objective rewards is narrower.

  • Rewarded: matching the training distribution's statistics; reasoning the way people do is not guaranteed. How a lower loss carries over to a task is measured, not promised (reading 3.5).
word vectors:a learned vectorper wordtask 1, from scratchtask 2, from scratchtask 3, from scratchnatural language processing (NLP): mostlyone model per task, sharing only word vectors(word2vec 2013, GloVe 2014)whole network,pretrained onunlabeled texttask 1task 2task 3adaptbeat task-specific architecturesacross the boardone pretrainednetwork, withenough scaletask 1task 2task 3no gradient updates (S20: prompting);S17 quoted itthrough the mid-2010s2018: ELMo, GPT, BERT's preprint2020: GPT-3

In about three years, adapting a pretrained model became the NLP default (S19 adapts one).

Self-check on the targets, one position's loss and a falling loss

Three questions on Part 1.

(a) A batch has 4 sequences of 9 tokens each. After the shift by one, how many predictions does each sequence give, and what shape are the logits?

(b) At one position the model gives the true next token probability \(1/4\). What is the loss at that position?

(c) Validation loss keeps going down. Does that show the model reasons the way people do?

(a) 8 predictions per sequence (inputs: tokens 1–8, targets: tokens 2–9); logits (4, 8, V).

(b) \(-\ln(1/4)=\ln4\approx1.39\).

(c) No. Its predictions match the statistics of its training text better; whether that helps on a task has to be measured.

That settles the objective. Next comes Part 2, the text it is computed on.

Five stages take the text from a web crawl to a training mixture

Part 2 · Data. The labels are the text, so the text decides what is learned. A typical pipeline for a trillion-token corpus, as GPT-3, T5's C4 corpus and The Pile describe it (reading 3.5):

1 · Crawla web crawl, oftenCommon Crawl (a publicarchive of billions ofpages), plus books,encyclopedias, code,papers2 · Extract and cleanstrip HTML boilerplate,menus, ads; detect thelanguage; dropdocuments too short,too repetitive ormostly symbols3 · Filter for qualityheuristics (punctuationratios, word lists) ora classifier for“reference-quality” text;judgment, and potentialbias, enters here4 · Deduplicateremove exact andnear-duplicatedocuments (the nextpages)5 · Mixa sampling weight persource: how manyepochs it gets, oftenless than one60%GPT-3's mixture: filtered Common Crawl was 60%
  • Weights are not sizes: GPT-3's mixture was 60% filtered Common Crawl, and Wikipedia was sampled for several epochs. Up-weighting a source risks overfitting it.

Duplicates cost twice, in memorized text and in test questions inside the training data

Stage 4 removes repetition nobody chose. Duplicates waste compute, but the two costs that matter are these:

Memorizationone 61-wordsentenceover 60,000 timesin C4 (Lee et al., 2022)trainmodelone 61-wordsentenceemits memorized textTrained on deduplicated data, models emitted memorized text about10× less often, at equal or better validation quality.Contaminationtraining crawltrainmodeltestbenchmarktest questionThe same question is in the crawl, so scoring the model onit measures memorization (S27).
  • Two kinds of duplicate: exact, the same text once case and spacing are normalized; near, a few characters or words changed. Comparing every pair of documents in full is quadratic in the corpus size: near duplicates are found with short summaries, an estimate, and banding, which avoids an all-pairs scan (reading 3.5).

Hashing finds exact duplicates, an overlap estimate near ones; reading 3.5's script does both.

Which of seven toy documents are exact copies once normalized?

Reading 3.5's deduplication script, stage 1 (exact). Each string stands for one document (in a real crawl, a whole web page); docs are numbered from 0. Its input, with the reading's comments, and normalize, which lowercases, drops the whitespace at both ends, and collapses every other run of whitespace to one space:


import hashlib
docs = [
    "The quick brown fox jumps over the lazy dog.",              # doc 0
    "Deep learning models improve with more data and compute.",  # doc 1
    "The quick brown fox jumps over the lazy dog.",              # doc 2: exact dup of 0
    "  the QUICK brown fox jumps over the lazy dog. ",           # doc 3: dup after normalizing
    "Deep learning models improve with more data & compute.",    # doc 4: near-dup of 1
    "Neural networks are trained with gradient descent.",        # doc 5
    "A completely unrelated sentence about lasagna recipes.",    # doc 6
]
def normalize(text):
    return " ".join(text.lower().split())
  

The comments name three copies; check them. What does normalize return for doc 3, and for doc 4? Which of docs 2–4 can stage 1, a test for equal normalized text, drop?

In stage 1, equal digests drop docs 2 and 3, and doc 4 survives

Answer: doc 3 becomes 'the quick brown fox jumps over the lazy dog.', as docs 0 and 2 do; doc 4 keeps "&" where doc 1 has "and". Stage 1 hashes each normalized copy: hashlib.sha1 gives a fixed-length digest, equal for equal texts.


# hashlib, docs, normalize: the previous page
seen, kept = {}, []
for i, doc in enumerate(docs):
    h = hashlib.sha1(normalize(doc).encode()).hexdigest()
    if h in seen:
        print(f"doc {i} is an exact duplicate of doc {seen[h]} (after normalizing)")
    else:
        seen[h] = i
        kept.append(i)
print(f"exact dedup: {len(docs)} docs -> {len(kept)} docs {kept}")
  
doc 0The quick…doc 1Deep learning…doc 2The quick…doc 3␣␣the QUICK…doc 4Deep learning…doc 5Neural networks…doc 6A completely…normalize, sha1first copy: keptsame digest as doc 0: droppeddocs 1 and 4, one word apart (and / &): different digestskept: [0, 1, 4, 5, 6]7 docs → 5Equal colors areequal digests. Thefigure is the printoutof the loop above.

seen maps each digest to its first document; catching doc 4 needs a measure of overlap.

The Jaccard similarity of two shingle sets measures near duplicates

To measure overlap, represent a document by its set of shingles: here the runs of 3 consecutive characters (3-grams) of its normalized text. The overlap of two sets \(A\), \(B\) is their Jaccard similarity, 1 for equal sets and 0 for disjoint ones:

\[J(A,B)=\frac{\lvert A\cap B\rvert}{\lvert A\cup B\rvert}\]
3-grams of the catthe␣catthehe␣e␣c␣cacatthe cat vs the catsthethehe␣he␣e␣ce␣c␣ca␣cacatcatatsthe catthe catsshared 5, union 6:J = 5/6 ≈ 0.83, a near duplicatethe cat vs the dogthethehe␣he␣e␣ce␣d␣ca␣docatdogthe catthe dogshared 2, union 8:J = 2/8 = 0.25␣ marks a space; shared shingles are shaded.
  • One changed word changes only the shingles that overlap it: a long document with one change keeps \(J\) near 1.

Exact \(J\) needs both full sets; the next page estimates it from 128 numbers per document.

In MinHash, two sets share their first shingle with probability \(J\)

The previous page's pair: the cat has 5 shingles, the cats the same 5 and 'ats', so \(J=5/6\).

the cat ∪ the cats, shuffled three times. Filled: in both documents; dashed: only in the cats; thick: the first shingle each document keeps.shuffle 1thehe␣cat␣caatse␣cthe cat keeps thethe cats keeps the✓sameshuffle 2e␣c␣cathehe␣atscatthe cat keeps e␣cthe cats keeps e␣c✓sameshuffle 3ats␣cacate␣che␣thethe cat keeps ␣cathe cats keeps ats✗differentEach shuffle is the order of one hash's values, smallest first (reading 3.5's first three hash pairs).
  • Shuffle the shingles of both documents; each document keeps its first shingle.
  • They keep the same one exactly when the first shingle is shared: probability \(J\) (here \(5/6\)).
  • Repeat with 128 shuffles; the fraction that agree estimates \(J\). A hash \((a\cdot x+b)\bmod p\) stands in for each shuffle, so the signature is 128 numbers per document.

Of the five survivors, docs 1 and 4 agree on 109 of 128 MinHash minima

Stage 2 of reading 3.5's script prints only the pairs with a true \(J>0.05\) or an estimate of at least 0.6:


pairwise similarity among the 5 surviving docs (threshold 0.6):
    pair  true Jaccard  MinHash est.  verdict
  (1, 4)        0.8571        0.8516  NEAR-DUP
  (1, 5)        0.0526        0.0391  -
  (4, 5)        0.0538        0.0469  -
  
128 minima, docs 1 and 4109 of 128 equal (blue): 109/128 = 0.8516Computed with reading 3.5's stage 2.
doc 1 …doc 4 …data␣and␣compute.data␣&␣compute.only in doc 1:only in doc 4:␣ana␣aandd␣cnd␣␣&␣&␣ca␣&53 and 51 shingles;48 shared, 56 in the union:J = 48/56 = 0.8571
  • The other two printed pairs share about 5% of their shingles; only (1, 4) passes 0.6.
  • More hash functions lower the estimate's variance at more storage and compute; production signatures use dozens to hundreds (reading 3.5).

MinHash estimates \(J\) from 128 random trials; the estimate is then compared with a threshold that people choose (here 0.6). Shingle size, the number of hashes, the threshold and the normalization are each a choice.

Deduplication is policy, and much data work is only partly documented

What those choices cost, what deduplication cannot catch, and two more facts about data (reading 3.5):

  • Threshold too low: legitimate reuse is deleted (license boilerplate, famous speeches, code idioms), which distorts the distribution. Too high: templated spam stays in, in bulk.
your corpus, deduplicatedbenchmarktest questionleakage across corpora: deduplication inside the corpusnever compares it with the benchmarkdecontamination: compare the corpus against the benchmark
  • Ask what the training corpus was and what decontamination the authors report; for many closed models (reachable only through an API) you cannot check.
  • The tokenizer is fixed before pretraining and frozen after (reading 3.5; S17: a checkpoint and its tokenizer are one artifact), so data and tokenizer decisions interact: a corpus with little code yields a tokenizer that splits code inefficiently.
  • Data quality has repeatedly mattered as much as architecture, and much of that work is documented only partially in public papers.

Self-check on Jaccard similarity, exact copies and contamination

Three questions on Part 2.

(a) The character 3-gram sets of data and date, and their \(J\)?

(b) Two documents differ only in capital letters and extra spaces. Which stage drops the second one, and how?

(c) Your corpus is thoroughly deduplicated. Can a benchmark score of a model trained on it still be contaminated?

(a) {'dat', 'ata'} and {'dat', 'ate'}: 1 shared of 3, \(J=1/3\).

(b) Exact deduplication: their normalized copies are the same text, so their digests are equal.

(c) Yes: deduplication removes repeats within the corpus. The benchmark's questions can still be in it once; decontamination checks the corpus against the benchmark.

That settles the data. Next comes Part 3, what training on it costs.

\(C\approx6ND\) counts 2 FLOPs per parameter forward and 4 backward

Part 3 · Compute. Cost in floating-point operations (FLOPs), for \(N\) parameters (not S17's \(N\) blocks) and \(D\) tokens:

forward, one tokenX1 × m×Wm × n=Z1 × n2mn FLOPs:a multiply andan add per weightbackward: 2mn, passed backdZ1 × n×WTn × m=dX1 × mbackward: 2mn, the updateXTm × 1×dZ1 × n=dWm × n
  1. Forward, one token. A product with an \(m\times n\) weight matrix costs about \(2mn\) FLOPs (S01's rule; S14's MAC); over all weights, \(2N\).
  2. Backward, one token. S05's rules \(dX=dZ\,W^\top\) and \(dW=X^\top dZ\), with \(dZ=\partial L/\partial Z\): two products of the same size, \(4N\).
  3. Together about \(6N\) per token; over \(D\) tokens, \(C\approx6ND\) FLOPs.
  4. Left out: all that is not a product with a weight: attention scores (no weights; they grow with the context length), normalization, softmax, activations.

The estimate counts weights only; the next page shows how much the rest adds.

One decoder layer costs \(24d^2\) per token in its weights and \(4Td\) in attention scores

Reading 3.5 counts one decoder layer's forward FLOPs per token, at width \(d\) and context length \(T\) (seq in its code):

  • Products with weights: \(Q,K,V\) \(6d^2\), output projection \(2d^2\), FFN \(16d^2\). In all \(24d^2\), twice the layer's \(12d^2\) weights (S16: \(4d^2\) attention, \(8d^2\) FFN).
  • Scores \(QK^\top\), weighted sum of values: \(2Td+2Td=4Td\), no weights (S14's \(2T^2d\) MACs per sequence: \(2Td\) MACs, \(4Td\) FLOPs, per token). Only these grow with \(T\).
one layer at d = 4,096 and T = 4,096: forward FLOPs per token, drawn to scaleQ, K, V: 6d22d2FFN: 16d2scores: 4Tdproducts with weights: 24d2 = 4.03×1084Td = 6.71×107

The weight products are the \(2N\) of the previous page; only the score term grows with \(T\).

Layer by layer, \(6N\) is within 16% at 1k–4k tokens and 6× off at 131k

That count for three configurations, in reading 3.5's printout:


GPT-2 small-ish: d=768, layers=12, seq=1024
  params N ~ 1.235e+08   forward/token 2.848e+08 FLOPs (= 1.15 * 2N)
  fwd+bwd/token 8.544e+08 FLOPs (= 1.15 * 6N)
7B-class: d=4096, layers=32, seq=4096
  params N ~ 6.574e+09   forward/token 1.529e+10 FLOPs (= 1.16 * 2N)
  fwd+bwd/token 4.588e+10 FLOPs (= 1.16 * 6N)
7B-class, long ctx: d=4096, layers=32, seq=131072
  params N ~ 6.574e+09   forward/token 8.187e+10 FLOPs (= 6.23 * 2N)
  fwd+bwd/token 2.456e+11 FLOPs (= 6.23 * 6N)
  
what 6ND assumesseq 1,0241.15 × 2Nseq 4,0961.16 × 2Nseq 131,0726.23 × 2N01234567forward FLOPs per token, in units of 2Nproducts with weights, head included: 2Nscores QKT and the weighted sum
  • At 1,024 and 4,096 tokens: 15–16% above \(6N\).
  • At 131,072: per layer, \(4Td\) is \(T/6d\approx5.3\) times \(24d^2\); the total is 6.23, not 6.33, because \(N\) also counts the embedding table.

Converted from FLOPs, Chinchilla's run is about 54,500 A100-days

FLOPs become time through a rate. Reading 3.5 uses an A100 GPU's peak in bf16 (a 16-bit float format), \(312\times10^{12}\) FLOP/s (NVIDIA datasheet), sustained at an assumed 40%. Its rows are published runs that Part 4 compares: Chinchilla (DeepMind, 2022), Meta's LLaMA-7B and Llama 2-7B (2023):


                 model         N         D  tok/param      C=6ND  A100-days
    Chinchilla (paper)   7.0e+10   1.4e+12       20.0   5.88e+23     54,532
      LLaMA-7B (paper)   7.0e+09   1.0e+12      142.9   4.20e+22      3,895
    Llama 2-7B (paper)   7.0e+09   2.0e+12      285.7   8.40e+22      7,790
  
C = 6 · 7.0×1010 · 1.4×1012= 5.88×1023 FLOPs4.71×109 s54,532 A100-daysabout 53 days÷ 0.4 · 312×1012= 1.248×1014 FLOP/s(40% of peak, assumed)÷ 86,400 s per day÷ 1,024 A100s
  • The 40% is an assumption: model FLOPs utilization (MFU), the share of peak spent on the model's required FLOPs, varies with model shape, hardware, parallelism and sequence length; a real plan measures it.

Self-check on a FLOP count, GPU-days and a longer context

Three questions on Part 3 (GPT-3's numbers from reading 3.5).

(a) GPT-3 has \(N=175\) billion parameters and was trained on \(D\approx300\) billion tokens. Its training compute \(C\), in FLOPs?

(b) In A100-days, at 40% of the \(312\times10^{12}\) FLOP/s peak?

(c) The 7B-class context grows from 4,096 to 131,072 tokens (32×). Which forward terms grow? Does \(6ND\) still hold?

(a) \(6\cdot1.75\cdot3\times10^{22}=3.15\times10^{23}\).

(b) \(C\) over \(1.248\times10^{14}\) FLOP/s is \(2.52\times10^{9}\) seconds: about 29,000 A100-days.

(c) Only the score terms, \(4Td\), grow (32×). Forward FLOPs go from 1.16 to 6.23 times \(2N\): \(6ND\) is about sixfold too low.

That settles compute. Next comes Part 4, on choosing \(N\) and \(D\) for a fixed \(C\).

Kaplan et al. (2020) found test loss to be a power law in \(N\), \(D\) and \(C\)

Part 4 · Scaling laws. One budget \(C\approx6ND\) buys a large \(N\) on a small \(D\), or the reverse. Which split gives the lowest loss? First, how the loss depends on each.

  • "Scaling Laws for Neural Language Models": over many Transformer language models, test loss falls as a smooth power law in \(N\) (parameters outside the embedding table), in \(D\) and in \(C\), across several orders of magnitude. Fitted, with constants \(N_c\) and \(D_c\):
\[L(N)\sim\left(\frac{N_c}{N}\right)^{\alpha_N},\ \alpha_N\approx0.076;\qquad L(D)\sim\left(\frac{D_c}{D}\right)^{\alpha_D},\ \alpha_D\approx0.095\]
×10×10×10N or D, log scale10.5L, log scale, relative to the left endL(N): slope −0.076L(D): slope −0.095×0.84 per 10× N (16% lower)×0.80 per 10× DEvery 10× multiplies L by the samefactor, so lowering the loss takesmultiplying resources, not addingto them.

\(\log L=\alpha_N\log N_c-\alpha_N\log N\): a straight line of slope \(-\alpha_N\).

Kaplan's allocation grows the model much faster than the data, and GPT-3 followed it

The paper's most consequential claim was about allocation: for a given \(C\), with \(C\approx6ND\), which \(N\) and \(D\) reach the lowest loss?

  • Compute-optimal: \(N\propto C^{0.73}\) and \(D\propto C^{0.27}\): 10× the compute is \(10^{0.73}\approx5.4\)× the parameters and \(10^{0.27}\approx1.9\)× the tokens (below).
Cwidth N, height D10× the compute (Kaplan)area ≈ 10×N × 5.4D × 1.9Each rectangle's width is N and itsheight is D, so its area is proportionalto the compute C ≈ 6ND.
  • And: at a fixed budget, a large model stopped well short of convergence beat a small one trained to convergence (p29 shows why this was later revised).
  • GPT-3 (2020): 175 billion parameters, trained on about 300 billion tokens: \(300/175\approx1.7\) tokens per parameter.

Two years later, a different experimental design gave a different split.

Chinchilla (2022) found that \(N\) and \(D\) both grow roughly as \(C^{0.5}\)

Hoffmann et al., "Training Compute-Optimal Large Language Models", trained over 400 models, up to 16B parameters and 500B tokens, with a different design. Their answer:

10× the computeCChinchilla: N × 3.2, D × 3.2Kaplan: N × 5.4, D × 1.9both areas ≈ 10×about the same training computeGopher: 280B parameters,300B tokens(≈1 token per parameter)Chinchilla: 70B parameters,1.4T tokens(20 tokens per parameter)4× smaller, about 5× more dataEach rectangle's width is Nand its height is D, so itsarea is proportional to thecompute C ≈ 6ND.
  • Compute-optimal \(N\propto C^{0.5}\) and \(D\propto C^{0.5}\).
  • The demonstration (right): at about the same compute, Gopher (≈1 token per parameter) was far from 20:1; Chinchilla, at 20:1, outperformed it across their evaluations, they report.
  • Rule of thumb: about 20 training tokens per parameter (\(1.4\times10^{12}/(7\times10^{10})=20\)).
  • What it optimizes: loss for a fixed training budget. It says nothing about the cost of using the model afterward.

With equal exponents, every budget gets 20 tokens per parameter

From exponents to sizes: reading 3.5 scales from Chinchilla's point, \(C_0=6\cdot70\times10^{9}\cdot1.4\times10^{12}=5.88\times10^{23}\). Three of its seven rows, and its two 100× lines, on log axes:

10191020102110221023102410251026108101010121014C, FLOPscountD_opt (tokens)N_opt (params)×202.887e+085.774e+09×202.887e+105.774e+11×202.887e+115.774e+12anchor: Chinchilla's run, C = 5.88e+23N = 70.0e9, D = 1.40e12100× the anchor's compute:Chinchilla-style, 20.0 tokens/paramN = 7.00e+11, D = 1.40e+13Kaplan-style, 2.4 tokens/paramN = 2.02e+12, D = 4.85e+12The labels are the printout ofreading 3.5's computation (threeof its seven rows and the two100× lines).
  • The rule: \(N=70\times10^{9}(C/C_0)^{a}\), \(D=1.4\times10^{12}(C/C_0)^{b}\), \(a=b=0.5\).
  • One row by hand, \(C=10^{23}\): \((10^{23}/(5.88\times10^{23}))^{0.5}=0.4124\); \(N=2.887\times10^{10}\), \(D=5.774\times10^{11}\): 20 per parameter, as in every row.
  • 100×: Kaplan's \(a=0.73\), \(b=0.27\) give \(100^{0.73}\approx28.8\)× the parameters, \(100^{0.27}\approx3.5\)× the tokens; Chinchilla's, 10× each. Illustrations, not measurements.

The two answers differ because the runs were set up differently

Both papers fit power laws to real measurements; the difference came down to experimental design (reading 3.5):

learning-rate schedule (S06)learning rate30B300BtokensKaplan: one schedule shared across sizes,warmup too, planned for a long runstopped at 30B: scored mid-decay,so small budgets look worseHoffmann: decays over the run's own budgetbest size for a fixed ClossN, log scaleHoffmann: fix C, vary N; take the minimum(one of three methods that agree)Kaplan: read from points partwayalong training curvesSchematic: shapes only, no measured values.
  • Parameters counted: Kaplan, only those outside the embedding table; Hoffmann, all of them.
  • Together, the later literature argues, Kaplan's choices bias the fit toward a bigger model on fewer tokens. Chinchilla credited the schedules; later re-analyses found other setup choices mattered more.

A scaling law is an empirical fit with a domain of validity: read the methods first.

Serving costs about \(2N\) per token, a reason to train smaller past 20:1

One more limit: 20:1 minimizes loss for a fixed training budget. Serving then costs about \(2N\) FLOPs per generated token (Part 3's forward count), for every user. Reading 3.5's case, the Llama 2-7B budget \(C=8.4\times10^{22}\):

  1. Chinchilla-optimal: \(D=20N\), so \(C=6N\cdot20N=120N^2\) and \(N=\sqrt{C/120}\approx2.6\times10^{10}\): about 26B parameters on \(D\approx530\)B tokens.
  2. Llama 2's choice: 7B parameters on 2 trillion tokens. A somewhat higher loss, but about \(26/7\approx3.7\) times cheaper per generated token, and it fits on one consumer GPU.
published runparameterstokenstokens per parameter
GPT-3 (2020)175B300B1.7
Chinchilla (2022)70B1.4T20
LLaMA-7B, Llama 2-7B (2023)7B1.0T, 2.0T143, 286
Llama 3 8B8Babout 15Tnearly 1,900
the same C = 8.4×1022Chinchilla-optimal:about 26B parameters,about 530B tokensLlama 2:7B parameters,2T tokensabout 3.7× cheaperserving: about 2N FLOPs per generated token

Past compute-optimal is a different objective, not a mistake; the first LLaMA paper says so.

A toy run trains one model at three widths on the same data and steps

Those laws were fit to hundreds of runs. What do three runs of your own show? Reading 3.5's script trains on 127,760 characters of a made-up language: chars its 17 characters, train_data the first 90%; CharLM: S17's decoder-only stack, one block, width \(d\); get_batch: 64 windows of 32 characters.


def train_one(d, n_head, steps=300, batch_size=64):
    torch.manual_seed(0)
    gen = torch.Generator().manual_seed(1)
    model = CharLM(len(chars), d, n_head, n_layer=1)
    n_params = sum(p.numel() for p in model.parameters())
    opt = torch.optim.AdamW(model.parameters(), lr=3e-3)
    for step in range(steps):
        x, y = get_batch(train_data, batch_size, gen)
        loss = F.cross_entropy(model(x).view(-1, len(chars)), y.view(-1))
        opt.zero_grad(); loss.backward(); opt.step()
    # ... evaluate mean loss on 20 held-out batches; return n_params, val_loss
print(f"{'d_model':>8} {'params':>10} {'val loss (nats/char)':>22}")
for d, n_head in [(8, 2), (32, 4), (128, 4)]:
    n_params, val_loss = train_one(d, n_head)
    print(f"{d:>8} {n_params:>10,} {val_loss:>22.4f}")
  

Predict: which width wins on held-out text? Does 32 → 128 gain more or less than 8 → 32?

Wider toy models do better, by less each time, but three runs cannot establish a scaling law

Answer: the widest model; and less. The printout (its first and last lines come from code not shown):


corpus: 127760 chars, vocab size 17
 d_model     params   val loss (nats/char)
       8      1,433                 1.1419
      32     14,897                 0.7343
     128    206,993                 0.6366
uniform-guess baseline: 2.8332 nats/char
  
0123held-out loss (nats/char)1,43314,897206,993parameters, log scaleuniform guess: ln 17 = 2.8332−0.41 nats for 10× the parameters−0.10 nats for 14×monotone over a 144× size rangeThree runs, one seed: the points are joined, no line is fitted.
  • It shows that capacity limits loss on structured data, consistent with smooth improvement under scaling.
  • It cannot establish a power law (nor rule one out): three sizes, one seed, 300 steps, a synthetic language, and no per-size tuning of hyperparameters, one of the setup choices behind the Kaplan–Chinchilla gap.

Self-check on a budget's split, a ratio of 2 and a model you will serve

Three questions on Part 4.

(a) At \(C=10^{23}\) the compute-optimal model has \(N=2.887\times10^{10}\) and \(D=5.774\times10^{11}\). With 100× less compute (\(C=10^{21}\)), what are \(N\) and \(D\)?

(b) GPT-3: about 2 tokens per parameter. Whose allocation? For that \(C\), what is Chinchilla's pick?

(c) Serving many users: the 20:1 model, or a smaller one trained longer?

(a) \(2.887\times10^{9}\) and \(5.774\times10^{10}\): each scales as \(C^{0.5}\), so each shrinks by \(\sqrt{100}=10\).

(b) Kaplan's (\(N\propto C^{0.73}\)). \(C=6N\cdot2N=12N^2\); \(N'=\sqrt{C/120}=N/\sqrt{10}\approx0.32N\) on \(20N'\approx6.3N\) tokens.

(c) The smaller one, if good enough: serving costs \(2N\) per token.

That settles scaling laws. Next comes Part 5, what scale is claimed to buy.

Emergent abilities (Wei et al., 2022), or an artifact of the metric?

Part 5 · Emergence. Loss falls smoothly with scale. Do task abilities?

  • Wei et al.: on tasks such as multi-step arithmetic and some BIG-Bench problems, models sit at chance, then jump (left). Emergent: absent in smaller models, present in larger ones, so not predictable by extrapolating smaller models.
  • Schaeffer, Miranda & Koyejo (2023): most claimed emergence appears under nonlinear or discontinuous metrics, such as exact match on a multi-digit answer, where almost right scores 0.
  • Their evidence: they re-scored several tasks with smoother metrics (right), such as token-level edit distance: how many tokens must change to reach the right answer; a harsh metric produced "emergence" even in ordinary autoencoders (autoencoders: S23).
Wei et al.: exact matchscoremodel scale, logSchaeffer et al.: the same models, a smoother metricscoremodel scale, logchanceat chance, then a jumpgradualSchematic: shapes only, no measured values.

Schaeffer's argument uses \(p^k\), the chance that all \(k\) tokens are right

An answer of \(k=10\) tokens, each right with probability \(p\), independently (a simplification). A smooth score, the expected fraction of tokens right, is \(p\); exact match needs all ten: \(p^{10}\). Let \(p\) rise in equal steps:


k = 10                       # tokens in the answer
print(f"{'p':>4} {'p**k':>8}")
for p in [0.5, 0.6, 0.7, 0.8, 0.9, 1.0]:
    print(f"{p:4.1f} {p ** k:8.4f}")
  

   p     p**k
 0.5   0.0010
 0.6   0.0060
 0.7   0.0282
 0.8   0.1074
 0.9   0.3487
 1.0   1.0000
  
0.50.60.70.80.91.0per-token accuracy p 00.51 score smooth score: p exact match: p10

Equal steps of 0.1 in \(p\) move exact match by 0.005, 0.022, 0.079, 0.241 and 0.651: near 0 for half the range, then most of its rise in the last two steps.

Per-token accuracy rising smoothly with size can look sudden under exact match.

Both can be true; so ask how a capability was measured

So is the jump real? Reading 3.5's summary:

  • Not contradictory: smooth loss curves and sharp task-level jumps can coexist. A score that needs many tokens right at once can rise sharply while each token's accuracy improves gradually, as \(p^{10}\) does.
  • It partly depends on the quantity you care about: if your system is graded by exact match, the jump is real for you.
  • Ask of every capability claim: measured how, on what metric, with how many models between the last "can't" and the first "can"?
  • And whether it can be checked: a scaling fit needs the runs, a contamination audit the corpus, "emerges at \(10^{23}\) FLOPs" checkpoints along the way (below: who publishes what).
parametersdatacodecheckpointsclosed modelopen-weightspublishedfully open (Pythia, OLMo)publishedpublishedpublishedpublishedA contamination audit needs the corpus;“emerges at 1023 FLOPs” needscheckpoints along the way.

Self-check on exact match, the plot to ask for and a jump that is real

Three questions on Part 5.

(a) Answers of \(k=5\) tokens, each right with \(p=0.8\). Exact match? Expected fraction of tokens right?

(b) Exact match is 2% for one model and 35% for a model 10× larger, with none in between. What do you ask for before calling it emergence?

(c) Your product is graded by exact match. Is that jump an artifact for you?

(a) \(0.8^5\approx0.33\); 0.8.

(b) Models in between, and a smooth score (log-likelihood of the answer, or partial credit) at every size. If the smooth score also jumps, that supports emergence; if it climbs steadily, the jump comes from exact match.

(c) No: under the metric you are scored on, the jump is real; the per-token gains behind it may still be smooth.

A jump counts as emergence only if it survives a smooth metric and the sizes in between; otherwise it may come from the metric.

Five mistakes in your own runs, each with its cause and its fix

Part 6 · Close. Five ways today's ideas go wrong in your own runs (reading 3.5's pitfalls):

symptomcausefix
in your scaling study, the bigger model does worseone learning rate reused across sizes; short budgets penalize large modelstune the learning rate at each size; compare at equal compute, not equal steps
great validation loss, but generations are memorized training textduplicated documentsdeduplicate before training; check that train and validation share no near duplicates
a capability "emerges" between two model sizespossibly a discontinuous metric over a smooth quantityalso plot a smooth quantity: the answer's log-likelihood, partial credit
the model sized at 20 tokens per parameter is too costly to servethe rule optimizes training compute onlydecide the serving budget first; train the model you can afford to serve past 20:1
a loss curve extrapolated from three small runstoo few points, one seedfit on many runs, report the fitting range, do not extrapolate far beyond it

Today's question gets five answers, from one objective to the metric

Back to the title page's question, clause by clause.

  • Why it is enough: the text supplies every label, and predicting text well needs what the text depends on. Rewarded: matching the training distribution's statistics; nothing more is guaranteed.
  • Which text: crawled, cleaned, filtered, deduplicated (exact by hashing; near by MinHash, an estimate of Jaccard similarity), mixed.
  • What it costs: \(C\approx6ND\) FLOPs, within about 16% at ordinary context lengths; Chinchilla's run is about 54,500 A100-days at 40% of peak.
  • How to split \(C\): \(N\propto C^{0.5}\), \(D\propto C^{0.5}\), about 20 tokens per parameter, for training compute; train past it when serving dominates.
  • Which claims hold up: a jump in exact match can come from smooth per-token gains (\(p^k\)); ask how, on what metric, with how many models in between.

For next time

  • Next session (S19), Monday: fine-tuning and parameter-efficient adaptation: LoRA and friends.
  • Read: 3.6 Fine-Tuning & LoRA.
  • HW3 (Transformer from scratch) is out today: due the Monday after next (S22).
  • Project: the proposal is due at the end of the week after next (the S23 week).
  • Quiz 3 (Module 3), two weeks from today (S23), covers today's material.