Scaling Laws, Compute Budgets and Pretraining Data
A pretraining run of a large model costs millions of dollars and cannot be repeated with different settings. Teams therefore decide the model size, the number of training tokens and the data mix before the run, by extrapolating from many small runs. The tools are scaling laws: empirical power laws that predict the loss from the number of parameters , the number of training tokens and the compute . This lesson does the arithmetic of compute budgets, fits a scaling law with SciPy, finds the compute-optimal split, weighs training against inference cost, and then turns to the other half of pretraining: where the tokens come from and how they are cleaned, deduplicated and checked for benchmark contamination. The math of power laws is in Scaling Laws and the FLOP counting in Counting Parameters and FLOPs.
Compute:
A forward pass through a dense transformer costs about floating-point operations per token (one multiply and one add per weight), the backward pass about twice that. Training on tokens therefore costs
(attention adds a term proportional to the context length, small for typical sizes). The example applies it to published models and inverts it for budgets, using the rule of thumb from the Chinchilla paper (Hoffmann et al., 2022) that a compute-optimal model sees about 20 tokens per parameter: with , and .
import math
models = [ # (name, parameters N, training tokens D), as published
("GPT-3", 175e9, 300e9),
("Gopher", 280e9, 300e9),
("Chinchilla", 70e9, 1.4e12),
("Llama 2 7B", 7e9, 2e12),
("Llama 3 8B", 8e9, 15e12),
]
print("model N D C = 6ND tokens per parameter")
for name, N, D in models:
print(f"{name:11s} {N / 1e9:5.0f}B {D / 1e12:6.2f}T {6 * N * D:9.2e} FLOP {D / N:7.1f}")
# Compute-optimal split under the rule of thumb D = 20 N: C = 6 N (20 N) = 120 N^2.
print("\nbudget C N_opt D_opt")
for C in (1e18, 1e21, 5.9e23, 1e25):
N = math.sqrt(C / 120)
print(f"{C:8.1e} {N / 1e9:8.3f}B {20 * N / 1e9:9.1f}B tokens")
# What does a budget mean in hardware time? One accelerator at 400 TFLOP/s peak, 40% utilisation.
C = 6 * 70e9 * 1.4e12
seconds = C / (400e12 * 0.4)
print(f"\nChinchilla-sized run: {seconds / 86400:,.0f} accelerator-days at 160 TFLOP/s sustained")model N D C = 6ND tokens per parameter
GPT-3 175B 0.30T 3.15e+23 FLOP 1.7
Gopher 280B 0.30T 5.04e+23 FLOP 1.1
Chinchilla 70B 1.40T 5.88e+23 FLOP 20.0
Llama 2 7B 7B 2.00T 8.40e+22 FLOP 285.7
Llama 3 8B 8B 15.00T 7.20e+23 FLOP 1875.0
budget C N_opt D_opt
1.0e+18 0.091B 1.8B tokens
1.0e+21 2.887B 57.7B tokens
5.9e+23 70.119B 1402.4B tokens
1.0e+25 288.675B 5773.5B tokens
Chinchilla-sized run: 42,535 accelerator-days at 160 TFLOP/s sustained
- GPT-3 (2020) and Gopher (2021) were trained on 300 billion tokens, 1.7 and 1.1 tokens per parameter: by the Chinchilla analysis, far too large for their data. Chinchilla used about the same compute as Gopher ( against FLOP) on a 4 times smaller model with 4.7 times more data, and outperformed it on most benchmarks.
- Llama 2 7B (286 tokens per parameter) and Llama 3 8B (1875) are trained far beyond compute-optimal on purpose, for the reason in the inference section below.
- A budget of FLOP gives back Chinchilla's 70B parameters and 1.4T tokens, as it should. At a sustained 160 TFLOP/s (a modern accelerator at 40% utilisation), that is 42,535 accelerator-days, for example about 1000 accelerators for 6 weeks.
Fitting a scaling law
Loss as a function of model size, with data and training otherwise scaled sensibly, follows a power law with a floor:
is the irreducible loss, the entropy of the text itself, which no model can beat (the generator floor of the tiny GPT is the toy version). The example generates noisy loss values for 8 model sizes from a known law, fits it with curve_fit on the 6 smallest, and checks the prediction for the 2 largest: the way a real team uses small runs to predict a big one.
import numpy as np
from scipy.optimize import curve_fit
# Synthetic "final validation loss" of models of 8 sizes, generated from a known law plus noise.
rng = np.random.default_rng(0)
E_true, A_true, alpha_true = 1.8, 400.0, 0.33
N = np.array([1e6, 3e6, 1e7, 3e7, 1e8, 3e8, 1e9, 3e9])
L = E_true + A_true / N ** alpha_true + rng.normal(0, 0.01, N.size)
def law(logN, E, A, alpha): # fit in log N for numerical sanity
return E + A * np.exp(-alpha * logN)
small = N <= 3e8 # fit on the 6 small models, keep the 2 largest to test extrapolation
params, _ = curve_fit(law, np.log(N[small]), L[small], p0=[2.0, 100.0, 0.3], maxfev=20000)
E, A, alpha = params
print(f"fitted: E = {E:.3f}, A = {A:.1f}, alpha = {alpha:.3f} (true 1.8, 400, 0.33)")
for n, l in zip(N[~small], L[~small]):
print(f"N = {n:.0e}: predicted {law(np.log(n), *params):.3f}, observed {l:.3f}")
# Without the floor E, a pure power law is a straight line in log-log space, and it extrapolates worse.
slope, intercept = np.polyfit(np.log(N[small]), np.log(L[small]), 1)
print(f"pure power law L = {np.exp(intercept):.2f} N^{slope:.4f}: predicts {np.exp(intercept) * 3e9 ** slope:.3f} at N = 3e9")
print(f"irreducible loss E: the fitted law never goes below {E:.3f}, however large the model")fitted: E = 1.798, A = 397.2, alpha = 0.329 (true 1.8, 400, 0.33)
N = 1e+09: predicted 2.228, observed 2.242
N = 3e+09: predicted 2.097, observed 2.108
pure power law L = 49.87 N^-0.1575: predicts 1.605 at N = 3e9
irreducible loss E: the fitted law never goes below 1.798, however large the model
The fit recovers , , (true values 1.8, 400, 0.33), and predicts 2.228 and 2.097 for the two held-out sizes against observed 2.242 and 2.108: off by about 0.01, the size of the noise. A pure power law without the floor, a straight line in log-log space, predicts 1.605 at parameters, far too optimistic: near the floor the curve bends and straight-line extrapolation fails. In real studies the exponents are small (Kaplan et al., 2020, reported for when data is not a constraint), which is why each constant improvement in loss needs a multiplicative increase in size.
The compute-optimal split
For a fixed budget a bigger model sees fewer tokens. The Chinchilla paper fitted a law in both variables,
with published constants , , , , , and minimised it under the budget constraint. Setting the derivative to zero gives and , both close to : scale parameters and tokens equally. The example does the minimisation numerically and also asks the question that matters for deployment.
import numpy as np
# Parametric loss fitted in the Chinchilla paper (Hoffmann et al., 2022, "approach 3").
E, A, B, alpha, beta = 1.69, 406.4, 410.7, 0.34, 0.28
def loss(N, D):
return E + A / N ** alpha + B / D ** beta
# 1. Compute-optimal split: for a budget C = 6ND, scan N and pick the lowest loss.
Ns = np.logspace(8, 12, 4001)
for C in (1e21, 5.9e23, 1e25):
D = C / (6 * Ns)
i = int(np.argmin(loss(Ns, D)))
print(f"C = {C:.1e}: best N = {Ns[i] / 1e9:6.1f}B, D = {D[i] / 1e9:7.0f}B tokens, "
f"D/N = {D[i] / Ns[i]:4.1f}, loss {loss(Ns[i], D[i]):.3f}")
# 2. Training + inference. Same target loss as a 70B model trained on 1.4T tokens:
target = loss(70e9, 1.4e12)
print(f"\ntarget loss {target:.3f}")
for N in (70e9, 35e9, 20e9):
# tokens needed to reach the target with N parameters: solve B / D^beta = target - E - A / N^alpha
D = (B / (target - E - A / N ** alpha)) ** (1 / beta)
train = 6 * N * D
for served in (1e12, 1e14):
total = train + 2 * N * served # inference: about 2N FLOP per generated token
print(f"N = {N / 1e9:3.0f}B: D = {D / 1e12:5.2f}T, train {train:.2e}, "
f"serve {served:.0e} tokens -> total {total:.2e} FLOP")C = 1.0e+21: best N = 1.8B, D = 91B tokens, D/N = 50.1, loss 2.329
C = 5.9e+23: best N = 32.5B, D = 3025B tokens, D/N = 93.0, loss 1.930
C = 1.0e+25: best N = 116.9B, D = 14251B tokens, D/N = 121.9, loss 1.845
target loss 1.937
N = 70B: D = 1.40T, train 5.88e+23, serve 1e+12 tokens -> total 7.28e+23 FLOP
N = 70B: D = 1.40T, train 5.88e+23, serve 1e+14 tokens -> total 1.46e+25 FLOP
N = 35B: D = 2.36T, train 4.96e+23, serve 1e+12 tokens -> total 5.66e+23 FLOP
N = 35B: D = 2.36T, train 4.96e+23, serve 1e+14 tokens -> total 7.50e+24 FLOP
N = 20B: D = 4.34T, train 5.21e+23, serve 1e+12 tokens -> total 5.61e+23 FLOP
N = 20B: D = 4.34T, train 5.21e+23, serve 1e+14 tokens -> total 4.52e+24 FLOP
Two lessons, one about the method and one about the economics.
- The method. This parametric fit puts the optimum at 50 to 122 tokens per parameter, not 20, and at Chinchilla's budget it prefers a 32.5B model on 3T tokens to the 70B model actually trained. The paper's three estimation approaches did not agree perfectly; the 20-tokens-per-parameter rule comes from the other two, and a 2024 replication (Besiroglu et al., arXiv 2404.10102) argued that the published parametric constants were poorly estimated and that a refit of approach 3 agrees with the other two. Treat "about 20 tokens per parameter" as a rule of thumb with a wide band, and fit your own law on your own data and architecture before betting a budget on it.
- The economics. Compute-optimal means optimal for training only. Serving costs about FLOP per generated token. To reach the same loss as the 70B model, a 20B model needs 4.34T tokens instead of 1.4T, so its training costs about the same ( against FLOP), but every served token is 3.5 times cheaper. If the model will generate tokens in its life, the total is for the 20B model against for the 70B one. That is why widely deployed models like Llama 3 8B are trained on far more tokens than "optimal": the extra training is paid once, the smaller model saves on every request. The limit is data: high-quality text is finite, and repeating it more than a few epochs gives diminishing returns.
Pretraining data
The tokens are the other half of a scaling law: the constants , , are properties of the data, and better data shifts the whole curve down. A pretraining corpus is built by a pipeline in which each stage removes part of what came in:
- Sources. Web crawls (Common Crawl, filtered into corpora such as C4, RefinedWeb or FineWeb), code (GitHub-derived sets such as The Stack, with licence filtering), books, scientific papers, Wikipedia, forums. The mix (how many tokens from each source, how many epochs) is a tuned hyperparameter; code and maths are often up-weighted because they help reasoning.
- Extraction and language ID. HTML to text without menus and boilerplate; a fastText-style classifier keeps the target languages.
- Quality filtering. Heuristics (length, share of letters, stop words, repeated lines, symbol ratios) remove spam and junk; a classifier trained to recognise "reference-like" text (for example Wikipedia-cited pages against random web pages) ranks the rest.
- Deduplication. Exact duplicates by hashing normalised text, near-duplicates (the same article with a different footer, templated pages) by MinHash. Duplicates waste compute and increase memorisation of the repeated text.
- Decontamination. Remove training documents that contain benchmark questions, or flag the benchmark items that appear in training data.
- Privacy and licensing. Remove or mask personal data (emails, phone numbers), respect robots.txt and opt-out requests, and track licences. Whether training on copyrighted text without permission is lawful is contested and under litigation in several countries; consent and attribution are ethical questions as well as legal ones.
Quality heuristics
Rule-based filters are cheap and transparent. The example scores six pages on five signals and keeps a page only if all of them pass; English stop words come from scikit-learn's built-in list.
import re
from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS
pages = [
"The ferry to the island leaves twice a day. In winter the evening crossing is cancelled when the wind is strong.",
"BUY NOW!!! best price $$ click here click here click here >>> www.example.test <<<",
"Home | About | Contact | Home | About | Contact | Login | Register",
"ferry ferry ferry ferry ferry ferry ferry ferry ferry ferry ferry ferry",
"Our bakery uses flour from the mill in the valley and opens at seven every morning except Monday.",
"x9#k2 @@ 0x3f;; ~~ ## 77 :: ||",
]
def quality(t):
words = re.findall(r"[A-Za-z']+", t)
n = max(len(words), 1)
return {
"words": len(words),
"alpha": sum(c.isalpha() for c in t) / max(len(t), 1), # share of letters
"stop": sum(w.lower() in ENGLISH_STOP_WORDS for w in words) / n, # real prose has many stop words
"unique": len({w.lower() for w in words}) / n, # low = repetitive
"symbols": sum(not (c.isalnum() or c.isspace() or c in ".,'") for c in t) / n, # |, $, #, ! per word
}
def keep(q):
return (q["words"] >= 8 and q["alpha"] >= 0.6 and q["stop"] >= 0.2
and q["unique"] >= 0.5 and q["symbols"] <= 0.1)
for t in pages:
q = quality(t)
print(f"{'KEEP' if keep(q) else 'drop'} words {q['words']:2d} alpha {q['alpha']:.2f} stop {q['stop']:.2f} "
f"unique {q['unique']:.2f} symbols {q['symbols']:.2f} | {t[:30]}")
# Contamination: does a benchmark item appear (in n-grams) in the training data?
train_text = " ".join(pages).lower()
benchmark = [
"In winter the evening crossing is cancelled when the wind is strong. True or false?",
"Which flour does the bakery use, and when does it open on Mondays?",
"What is the boiling point of water at sea level in degrees Celsius?",
]
def ngrams(t, n=8):
w = re.findall(r"[a-z']+", t.lower())
return {" ".join(w[i:i + n]) for i in range(len(w) - n + 1)}
train_grams = ngrams(train_text)
for b in benchmark:
g = ngrams(b)
hit = len(g & train_grams) / max(len(g), 1)
print(f"{hit:.2f} of its 8-grams in training data: {'CONTAMINATED' if hit > 0 else 'clean'} | {b[:45]}")KEEP words 21 alpha 0.80 stop 0.48 unique 0.81 symbols 0.00 | The ferry to the island leaves
drop words 13 alpha 0.67 stop 0.31 unique 0.69 symbols 0.92 | BUY NOW!!! best price $$ clic
drop words 8 alpha 0.68 stop 0.25 unique 0.62 symbols 0.88 | Home | About | Contact | Home
drop words 12 alpha 0.85 stop 0.00 unique 0.08 symbols 0.00 | ferry ferry ferry ferry ferry
KEEP words 18 alpha 0.81 stop 0.56 unique 0.94 symbols 0.00 | Our bakery uses flour from the
drop words 4 alpha 0.13 stop 0.00 unique 0.75 symbols 3.25 | x9#k2 @@ 0x3f;; ~~ ## 77 :: ||
0.62 of its 8-grams in training data: CONTAMINATED | In winter the evening crossing is cancelled w
0.00 of its 8-grams in training data: clean | Which flour does the bakery use, and when doe
0.00 of its 8-grams in training data: clean | What is the boiling point of water at sea lev
The two prose pages pass. The spam page and the navigation menu fail on symbols per word (0.92 and 0.88: !, $, >, |), the repeated "ferry" page on stop words (0.00) and unique words (0.08), and the line noise on everything. Each threshold is a choice that silently removes some legitimate text too (poetry, code, tables, lists, dialects with different stop words), so real pipelines measure what each filter removes and check the downstream effect on small models.
Contamination. The last lines check benchmark items against the training text by 8-gram overlap: 62% of the first question's 8-grams appear verbatim in the ferry page, so a model that scores well on it may be remembering rather than reasoning. GPT-3's analysis used 13-gram overlap; short n-grams flag more false positives, long ones miss paraphrases. A contaminated benchmark is not a fair test, and the honest options are to remove the overlapping training documents before training, or to report results on the clean subset.
Near-duplicates with MinHash
Exact hashing only catches identical text. Near-duplicates are measured by the Jaccard similarity of the documents' sets of word -grams ("shingles"), . Comparing all pairs of a billion documents is impossible, so each document is summarised by a MinHash signature: for each of random hash functions , keep the minimum hash over the document's shingles. For one random hash function, the probability that two documents share the minimum equals their Jaccard similarity:
so the fraction of agreeing positions in two signatures estimates . Locality-sensitive hashing then splits each signature into bands of rows and only compares documents that agree on all rows of at least one band; a pair with similarity becomes a candidate with probability , a steep S-curve.
import hashlib
import re
import numpy as np
docs = {
"a": "The night ferry leaves the harbour at ten and reaches the island before dawn. Tickets are sold on board.",
"b": "The night ferry leaves the harbour at ten and reaches the island before dawn. Tickets are sold at the pier.",
"c": "the night ferry leaves the harbour at ten and reaches the island before dawn. Tickets are sold on board!",
"d": "Fresh bread is baked every morning in the village and sold until noon at the square.",
"e": "Fresh bread is baked every morning in the village and sold until noon in the square. Closed on Sundays.",
"f": "The museum opens at nine. Entry is free for children and students on the first Sunday of the month.",
}
# 1. Exact dedup: hash of the normalised text (lower case, letters and digits only, single spaces).
norm = lambda t: " ".join(re.findall(r"[a-z0-9]+", t.lower()))
exact = {}
for k, t in docs.items():
exact.setdefault(hashlib.sha1(norm(t).encode()).hexdigest(), []).append(k)
print("exact duplicate groups after normalising:", [g for g in exact.values() if len(g) > 1])
# 2. Near-duplicates: Jaccard similarity of word 3-gram shingles, estimated with MinHash.
def shingles(t, n=3):
w = norm(t).split()
return {" ".join(w[i:i + n]) for i in range(len(w) - n + 1)}
P = 2_147_483_647 # a large prime; hash functions h(x) = (a x + b) mod P
K = 128
rng = np.random.default_rng(0)
a, b = rng.integers(1, P, K), rng.integers(0, P, K)
def minhash(sh):
x = np.array([int(hashlib.md5(s.encode()).hexdigest()[:8], 16) % P for s in sh], dtype=np.int64) # < 2^31: no overflow
return ((a[:, None] * x[None, :] + b[:, None]) % P).min(axis=1) # K minimums = the signature
S = {k: shingles(t) for k, t in docs.items()}
sig = {k: minhash(s) for k, s in S.items()}
print("pair true Jaccard MinHash estimate")
for p, q in [("a", "b"), ("a", "c"), ("d", "e"), ("a", "d"), ("a", "f")]:
true = len(S[p] & S[q]) / len(S[p] | S[q])
est = float((sig[p] == sig[q]).mean())
print(f"{p}-{q} {true:10.3f} {est:10.3f}")
# 3. LSH banding: 32 bands of 4 rows; documents sharing any band become candidate pairs.
bands, rows = 32, 4
buckets = {}
for k, s in sig.items():
for i in range(bands):
buckets.setdefault((i, tuple(s[i * rows:(i + 1) * rows].tolist())), set()).add(k)
cands = sorted({tuple(sorted(v)) for v in buckets.values() if len(v) > 1})
print("candidate groups from LSH:", cands)
print(f"P(candidate) at Jaccard 0.5: {1 - (1 - 0.5 ** rows) ** bands:.3f}, at 0.2: {1 - (1 - 0.2 ** rows) ** bands:.3f}")exact duplicate groups after normalising: [['a', 'c']]
pair true Jaccard MinHash estimate
a-b 0.750 0.781
a-c 1.000 1.000
d-e 0.550 0.539
a-d 0.000 0.000
a-f 0.000 0.000
candidate groups from LSH: [('a', 'b', 'c'), ('a', 'c'), ('d', 'e')]
P(candidate) at Jaccard 0.5: 0.873, at 0.2: 0.050
- Normalising (lower case, letters and digits only) makes a and c identical: they differed only in case, spacing and "!" versus ".". One hash catches them.
- a and b (a different last sentence) have Jaccard 0.750, estimated as 0.781 from 128 hashes; d and e 0.550, estimated 0.539. The estimate's standard error is about , 0.04 here.
- With 32 bands of 4 rows, LSH puts a, b, c in one bucket and d, e in another, and never compares the unrelated pages. Pairs with become candidates with probability 0.873, pairs with with 0.050; candidates are then verified with the full signature, and one document per cluster is kept.
Pitfalls
- Extrapolating a straight line in log-log space. Without the floor , predictions for large models are far too optimistic (1.605 against about 2.1 in the example).
- Treating "20 tokens per parameter" as a law. It depends on the data, the architecture and the fitting method, and it ignores inference cost.
- Comparing losses across tokenizers or datasets in a scaling study. Scaling laws are fitted per tokenizer and data mix; changing either changes the constants.
- Deduplicating only exactly. Templated pages, mirrors and boilerplate variations survive exact hashing; use near-duplicate detection, and deduplicate across the training and evaluation sets too.
- Filtering without measuring what is removed. Heuristics and quality classifiers encode a notion of "good text" that can remove dialects, minority languages and specialist content; audit samples of what each filter drops.
- Ignoring licences, consent and personal data. Record the source and licence of every component; respect opt-outs; remove personal data. Problems found after training are very expensive to fix.
Practice
- Using , what model size and token count are compute-optimal for FLOP? How long would it take at 160 TFLOP/s sustained on 64 accelerators?
Answer
(9.1B parameters), B tokens. Time: s, about 11 days.
- In
sl2.py, raise the noise from 0.01 to 0.05 (rng.normal(0, 0.05, N.size)). Do the fitted constants and the predictions for the two largest models still hold?
Answer
The constants barely move (, , ), and the predictions are 2.226 and 2.094 against observed 2.294 and 2.146: errors of 0.05 to 0.07, about the size of the noise in the observed points themselves. The fit is robust here because the data were generated from exactly the fitted form. Real loss curves are only approximately power laws, which is why real studies use many sizes over several orders of magnitude and still report uncertainty bands.
- With bands of rows, what is the probability that a pair with Jaccard 0.8 becomes a candidate? How would you change and to make pairs below 0.5 rarer?
Answer
(about ). Increasing (more rows per band) moves the S-curve's threshold up and makes it steeper; for example , puts the threshold near .
- A benchmark question has 20 words. How many 13-grams does it have, and what is the weakness of declaring it clean when none of them occur in the training data?
Answer
13-grams. Clean by this test only means no 13 consecutive words match: a paraphrased, translated or reformatted copy of the question and answer would pass undetected.
Test yourself
About how many FLOP does training a 7B-parameter model on 2T tokens take?
What does the term in represent?
- The learning rate
- The irreducible loss, the entropy of the data that no model can beat
- The number of epochs
- The loss of a model with one parameter
Why are widely deployed models such as Llama 3 8B trained on far more than 20 tokens per parameter?
- Because compute-optimal training is impossible
- A smaller model trained longer reaches the same loss and is cheaper for every token served
- Because more tokens reduce the model size
- Because of the KV cache
A MinHash signature of 128 hashes agrees with another in 100 positions. What is the estimated Jaccard similarity?
- 0.128
- 0.781
- 1.0
- 0.5
A benchmark item's 8-grams appear verbatim in the training data. What is the right response?
- Report the score as usual
- Treat it as contaminated: remove the overlapping documents before training or report results on the clean subset
- Retrain with a larger model
- Shorten the n-grams to 3