Search Tech Journey

Find topics, journeys and posts

6-month learning plan114 / 130
back to blog
llmadvanced 50m read

S114 · Scaling Laws — Chinchilla, Compute-Optimal Training

The empirical laws (Kaplan 2020, Chinchilla 2022) that predict how big a model to train given a fixed compute budget — and why the '20 tokens per parameter' rule made LLaMA-3 possible.

LLMsM13 · NLP & Transformers· Session 114 of 130 90 min

🎯 Explain why LLM providers pick the model sizes they do, using compute budget, dataset tokens, and the Chinchilla 20-tokens-per-parameter rule.

Why this session exists

Every LLM you use — GPT-4, Claude 3, Gemini, Llama 3, Qwen 2.5 — was sized by someone doing a Chinchilla calculation. If you don't understand that calculation, half of the modelling news feed reads like magic ("why did Meta pick 70B?", "why is Gemini Flash so cheap?"). This session teaches you the two seminal papers (Kaplan 2020, Hoffmann 2022), the pretty formula they distilled the scaling universe into, and the practical implication: for a fixed number of GPUs and days, there is exactly one model size that is optimal.

You will be able to
  • Explain the Kaplan (OpenAI) and Chinchilla (DeepMind) findings without opening a paper.
  • Given a compute budget in FLOPs, estimate the compute-optimal model size and training tokens.
  • Apply the '20 tokens per parameter' rule of thumb and know when it breaks (inference vs training).
  • Read a modern LLM release ('trained on 15T tokens with 405B params') and instantly know if it's under- or over-trained.
  • Explain why LLaMA-3 is 'over-trained on purpose' relative to Chinchilla-optimal.

Prerequisites

  • S112 · BERT/GPT/T5 — you need to know what a decoder-only LLM is and what its parameters are.
  • S102 · CNNs is helpful for intuition on 'bigger model + more data = lower loss'.
  • Basic sense of orders of magnitude and unit prefixes (10¹⁸ = exa-).


(a) Intuition · 5 min

Building a house with a fixed budget
🌍 Real world

You have $1M to build a house. You can spend it on square footage (a bigger house) or on interior finish (higher quality per square foot). Spend it all on square footage → cavernous rooms with concrete floors. Spend it all on finish → a jewel-box studio.

Somewhere in the middle is the 'best house for $1M'. If someone gave you a formula that took your budget and told you the optimal size + finish level, you'd use it every time.

💻 Code world

Training an LLM has the same shape. You have a fixed compute budget (FLOPs, i.e. GPU-days). You can spend it on more parameters (bigger model) or more training tokens (more data). Both reduce loss, but along different curves.

Chinchilla (2022) found that for a fixed compute budget, the compute-optimal split is roughly 20 tokens per parameter. A 70B model wants ~1.4T tokens. A 400B model wants ~8T tokens. Deviate too far and you're wasting compute in one dimension.

The five numbers you must internalise
  • Compute C ≈ 6 × N × D — where N is parameter count and D is training tokens. This is the FLOPs-of-training formula.
  • Kaplan (2020): scale N faster than D. Recommended ~1.5-2 tokens per parameter. GPT-3 (175B, 300B tokens) followed this.
  • Chinchilla (2022): scale N and D together. Recommended ~20 tokens per parameter. Chinchilla itself was 70B/1.4T — same compute as GPT-3, better loss.
  • Loss L(N, D) fits a power law: L = A/N^α + B/D^β + E. Chinchilla fit α≈0.34, β≈0.28.
  • Modern practice (LLaMA-3, Qwen, Mistral): DELIBERATELY over-train past Chinchilla ('over-training ratio' = 50-500 tokens/param). Why? Because inference is where money goes — a smaller model that took a bit more training compute is cheaper to serve forever.

The two-paper history

  1. 2020
    Kaplan et al. · OpenAI
    First rigorous scaling laws. Fits show N should scale much faster than D. This justifies going straight to GPT-3 (175B, 300B tokens).
  2. 2020
    GPT-3 released
    175B parameters trained on 300B tokens (1.7 tokens/param). Massively undertrained by later standards.
  3. 2022
    Hoffmann et al. · DeepMind (Chinchilla)
    Trains 400+ models across sizes, refits. Concludes GPT-3 was undertrained by 4×; a 70B model trained on 1.4T tokens beats it at same compute.
  4. 2023
    LLaMA-1
    Meta ships 7B, 13B, 33B, 65B — all trained on ~1T tokens (way past Chinchilla for the small ones). Open-source arms race begins.
  5. 2024
    LLaMA-3
    8B model trained on 15T tokens (1875 tokens/param, ~90× past Chinchilla). Sets the 'inference-optimised' pattern most 2026 LLMs follow.
  6. 2025
    Small-model renaissance
    Phi-3, Qwen-2.5, Gemma-2 — all deeply over-trained small models. The Chinchilla point is now the FLOOR, not the ceiling.

(b) Visual walkthrough · 15 min

The compute–loss universe

The two rules head-to-head

Kaplan 2020 (OpenAI)

Grow parameters faster than data

  • Optimal ratio: ~1.5–2 tokens/param
  • Justifies GPT-3 (175B, 300B tokens)
  • Later shown to underweight D by ignoring learning-rate schedule effects
  • Historical importance; not the modern rule
Chinchilla 2022 (DeepMind)

Grow both together

  • Optimal ratio: ~20 tokens/param
  • 70B/1.4T beats 175B/300B at same compute
  • Fit refined by Epoch AI 2024 — exponents very close but with caveats
  • The modern reference for training-optimal
Modern practice (2024+)

Over-train small models

  • Ratio 50–500 tokens/param
  • LLaMA-3-8B: 1875 tokens/param
  • Rationale: inference cost dominates lifetime
  • Chinchilla-optimal is the FLOOR, not the ceiling

The core formulas

1C
Pick a compute budget

e.g. 100 H100 GPUs × 30 days × 300 TFLOP/s (BF16 usable) ≈ 8 × 10^22 FLOPs.

2N*
Compute-optimal N

N* ≈ 0.6 × sqrt(C) — plug in C=8e22 → N* ≈ 5.4 × 10^10 params ≈ 54B model.

3D*
Compute-optimal D

D* = 20 × N* ≈ 1.08 × 10^12 tokens ≈ 1.1T tokens.

4check
Verify: 6·N·D ≈ C

6 × 5.4e10 × 1.1e12 ≈ 3.6e23 FLOPs — close to our budget (order-of-magnitude estimate).

5over
Decide over-train ratio

If inference cost matters, halve N and quadruple D. e.g. 27B / 4T tokens — same training compute, way cheaper serving.

What the papers plotted

The famous figures you'll see cited forever

Kaplan Fig. 1
Test loss vs compute across 3 axes (N, D, C). Log–log straight line. Established that scaling is smooth and predictable.
predictable
Chinchilla Fig. 1
IsoFLOP curves — for each fixed compute budget, plot loss as a function of N. Each curve has a minimum, and those minima trace the compute-optimal frontier.
isoFLOP
Chinchilla Table 3
Predicted N_opt and D_opt for compute budgets from GPT-3 scale to Gopher. Shows GPT-3 was under-data by ~4×.
table
Epoch AI replication (2024)
Refits the same data; finds the exponents are approximately right but the confidence intervals are large. Ratio 20 tokens/param stays as the industry rule of thumb.
replication

Common misconception
✗ What most people think

"Scaling laws say bigger models are better. So with a fixed compute budget I should train the largest model I can fit."

✓ What is actually true

Scaling laws describe a joint optimum over parameters and tokens under a compute constraint. For a fixed budget there is a specific model size that minimises loss, and models both smaller and larger than it are worse. The Chinchilla result was that the previous generation was systematically oversized and undertrained — the fix was a smaller model on far more data, at the same compute.

Why the myth is so sticky

Because the first widely-read scaling paper (Kaplan et al.) reported that model size mattered far more than data, and the industry optimised accordingly for a couple of years. That conclusion followed from a learning-rate schedule that was not re-tuned per run, which biased the fits. The lesson stuck harder than the correction — and "bigger model" is also the easier thing to announce.

Prove it to yourself

Minimise the Chinchilla-form loss under a fixed compute budget and watch an interior optimum appear:

import numpy as np
A, B, E, a, b = 406.4, 410.7, 1.69, 0.34, 0.28
C = 1e21                                  # FLOPs budget
N = np.logspace(8, 11, 200)               # params
D = C / (6 * N)                           # tokens, since C ~ 6*N*D
L = E + A/N**a + B/D**b
i = L.argmin()
print(f'best N={N[i]:.2e} params, D={D[i]:.2e} tokens, ratio D/N={D[i]/N[i]:.1f}')
print(f'loss at 10x larger model, same budget: {L[abs(N-10*N[i]).argmin()]:.4f} vs {L[i]:.4f}')
From first principles
Start with the question

Why is the loss a power law in parameters and data, with an irreducible constant added — rather than exponential decay, or decay to zero?

  1. 1
    Split the loss into three parts: entropy intrinsic to the data, error from a model too small to represent the true function, and error from too little data to identify the function you could represent.
    forced by · these are independent sources — approximation, estimation, and noise — and no amount of one fixes another
  2. 2
    The intrinsic entropy cannot be reduced by any model. Natural text has genuine unpredictability, so the loss has a floor E > 0.
    forced by · a perfect model of the true distribution still incurs its entropy; that is what cross-entropy measures
  3. 3
    The approximation term falls as capacity grows, but with diminishing returns: each new parameter captures a rarer, less frequent pattern. Language phenomena follow heavy-tailed (Zipf-like) frequency distributions.
    forced by · you learn the common patterns first because they carry the most gradient; what is left is progressively rarer
  4. 4
    Reducing loss by a fixed increment therefore requires covering an exponentially rarer slice of the tail — which under a heavy-tailed frequency distribution requires a multiplicative increase in capacity. Constant multiplicative cost per constant loss gain is a power law.
    forced by · "multiply resources by k to subtract δ from loss" integrates to L ∝ N−α
  5. 5
    The same argument runs independently for data: rare patterns need many tokens to be observed often enough to be learned rather than memorised, giving a second power-law term in D.
    forced by · estimation error shrinks with sample count, and rare events need proportionally more samples to appear
⇒ Therefore

Therefore L(N,D) = E + A/Nα + B/Dβ is the shape the tail structure of language forces. The additive constant is irreducible entropy; the two power laws are capacity and sample limits.

And note what this predicts: whichever term dominates is your actual bottleneck, and improving the other one is wasted money. It also predicts that scaling laws must eventually break — the data term assumes an unlimited supply of fresh tokens, and high-quality text is finite. That is precisely why the frontier has shifted toward data quality, synthetic data, and inference-time compute rather than raw parameter count.

Mental modelOne budget, two levers, a hard floor

Compute is a fixed pot: roughly C ≈ 6ND FLOPs for N parameters over D tokens. Spending it on parameters buys the ability to represent rarer patterns; spending it on tokens buys the evidence to actually learn them. Both curves are power laws with diminishing returns, and both sit on top of an irreducible entropy floor.

Because both terms decay, the optimum is interior. Overspend on either lever and you are strictly worse off at the same cost.

  • C ≈ 6ND for dense transformer training: 2 FLOPs per parameter forward, 4 backward.
  • Chinchilla-optimal is roughly 20 tokens per parameter — but that optimises training loss per FLOP, and says nothing about serving.
  • Loss is smooth and predictable in compute; specific capabilities are not. Aggregate loss curves hide sharp per-task transitions.
  • The floor E is real. No budget drives cross-entropy on natural text to zero.
🔔 Fires when you see

Fire this model the moment you see: a proposal to scale one dimension only · a training run whose loss curve is flattening · a "how much data do we need" question · someone citing tokens-per-parameter as a universal law · a decision between a bigger model and more epochs.

The tradeoff

You have a fixed training budget and a model you will serve for a year. Train Chinchilla-optimal, or deliberately overtrain a smaller model?

Chinchilla-optimal (~20 tokens/param)
+ you gain lowest achievable loss for the training compute you spent — the mathematically correct answer to the question "best model per training FLOP"
− you pay it optimises the wrong objective if you serve the model, because a larger model costs more per request forever; training compute is paid once, inference compute is paid per user per token
pick when research runs, scaling studies, or a model that will be trained and evaluated but not served at volume
Overtrained small model (100–1000+ tokens/param)
+ you gain far cheaper inference for a given quality level — fewer parameters means less memory, smaller KV cache, higher batch size, lower latency, and it may fit on hardware the bigger model cannot
− you pay strictly more training compute for the same loss, with sharply diminishing returns as you push past the optimum; and eventually you exhaust high-quality tokens and start repeating data
pick when the model will serve significant sustained traffic, so lifetime inference FLOPs will exceed training FLOPs — true for essentially every deployed product model
Mixture-of-Experts
+ you gain decouples total parameters from active parameters, so you get large-model quality at small-model FLOPs per token
− you pay all parameters must still be resident in memory, so serving memory does not shrink; routing adds load-balancing complexity and makes latency less predictable under skew
pick when you are memory-rich and FLOP-bound, and you can invest in the serving infrastructure MoE requires
What a senior engineer actually does

Chinchilla answers "best model per training FLOP". Almost nobody actually has that objective. The real objective is total cost of ownership over the model's serving lifetime, and under that objective overtraining a smaller model is usually correct — which is why every recent small open model is trained on token counts far beyond the Chinchilla point.

The decision rule is computable before you start: estimate lifetime inference tokens, multiply by 2N FLOPs per token, and compare against 6ND for training. If inference dominates by an order of magnitude, shrink the model and extend the run.


(c) Hands-on · 25 min

Compute-optimal calculator + fit visualisation. No GPUs needed — this is pure math on published numbers.

"""scaling_laws.py — compute-optimal LLM sizing calculator.
 
Given a compute budget in FLOPs, predict the compute-optimal model size
and training tokens using Chinchilla exponents. Also evaluate known LLMs
against the Chinchilla frontier and print how 'over-trained' each is.
"""
from __future__ import annotations
import math
from dataclasses import dataclass
 
# Chinchilla-fit constants (Hoffmann et al. 2022, Table A9).
# L(N,D) = A/N^ALPHA + B/D^BETA + E
A, ALPHA = 406.4, 0.34
B, BETA  = 410.7, 0.28
E        = 1.69
 
# Compute cost of one forward+backward pass through the whole dataset.
def compute_flops(n_params: float, n_tokens: float) -> float:
    """Kaplan/Chinchilla approximation: 6 × N × D."""
    return 6 * n_params * n_tokens
 
 
def chinchilla_loss(n_params: float, n_tokens: float) -> float:
    """Predicted loss under the Chinchilla parametric fit."""
    return A / n_params ** ALPHA + B / n_tokens ** BETA + E
 
 
def optimal_split(compute_flops: float) -> tuple[float, float]:
    """Given a training compute budget C, return compute-optimal (N, D).
 
    From Chinchilla Section 3: N_opt scales like C^0.5, D_opt = ~20 N_opt.
    """
    # Chinchilla's practical result: N_opt ≈ 0.6 * sqrt(C), D_opt ≈ 20 * N_opt.
    n_opt = 0.6 * math.sqrt(compute_flops)
    d_opt = 20 * n_opt
    return n_opt, d_opt
 
 
@dataclass
class LLM:
    name: str
    params: float
    tokens: float
 
    @property
    def flops(self) -> float:
        return compute_flops(self.params, self.tokens)
 
    @property
    def tokens_per_param(self) -> float:
        return self.tokens / self.params
 
    @property
    def chinchilla_optimal_params(self) -> float:
        return optimal_split(self.flops)[0]
 
    @property
    def over_train_ratio(self) -> float:
        """How many times MORE tokens/param than Chinchilla-optimal (20)."""
        return self.tokens_per_param / 20
 
 
MODELS = [
    LLM("GPT-3",       175e9,   300e9),
    LLM("Chinchilla",   70e9,   1.4e12),
    LLM("LLaMA-1-65B",  65e9,   1.4e12),
    LLM("LLaMA-2-70B",  70e9,   2.0e12),
    LLM("LLaMA-3-8B",    8e9,    15e12),
    LLM("LLaMA-3-70B",  70e9,    15e12),
    LLM("LLaMA-3-405B",405e9,    15e12),
    LLM("Qwen-2.5-7B",   7e9,    18e12),
]
 
print(f"{'model':<15}{'params':>10}{'tokens':>10}{'FLOPs':>12}"
      f"{'tok/param':>12}{'Chinch N*':>12}{'over×':>8}")
print("-" * 82)
for m in MODELS:
    print(f"{m.name:<15}"
          f"{m.params/1e9:>8.0f}B"
          f"{m.tokens/1e12:>8.1f}T"
          f"{m.flops:>12.1e}"
          f"{m.tokens_per_param:>12.1f}"
          f"{m.chinchilla_optimal_params/1e9:>10.1f}B"
          f"{m.over_train_ratio:>8.1f}×")
 
print("\n--- If YOU had 100 H100s × 30 days × 300 TFLOP/s BF16 ---")
c = 100 * 30 * 86400 * 300e12
n, d = optimal_split(c)
print(f"Budget       : {c:.2e} FLOPs")
print(f"Optimal N    : {n/1e9:.1f}B params")
print(f"Optimal D    : {d/1e12:.2f}T tokens")
print(f"Predicted loss: {chinchilla_loss(n, d):.3f}")

What each block does

Anatomy of the calculator

compute_flops(N, D) = 6·N·D
The Kaplan/Chinchilla FLOPs-per-training-run estimate. Factor 6 comes from 2 (multiply-accumulate) × 3 (forward + backward + optimiser).
cost
chinchilla_loss(N, D)
The empirical loss law with A, B, E, α, β fitted by DeepMind. Plug in any (N,D) to get predicted validation loss.
law
optimal_split(C)
The convenient closed-form: N* = 0.6·√C, D* = 20·N*. Derived by minimising loss subject to a compute constraint.
optimum
over_train_ratio
tokens_per_param / 20. Values >1 mean intentionally over-trained beyond Chinchilla (as LLaMA-3 is). Values <1 mean under-trained (as GPT-3 was).
diagnostic
The MODELS table
Real numbers from public model cards. Instantly shows GPT-3 was ~10× under-Chinchilla in tokens; LLaMA-3-8B is ~90× over-Chinchilla.
history
Try itReverse-engineer OpenAI's next model

Compute the budget:

gpus, days, tflops = 25000, 90, 400
C = gpus * days * 86400 * tflops * 1e12
n_opt, d_opt = optimal_split(C)
print(f"Compute        : {C:.2e} FLOPs")
print(f"Chinchilla N*  : {n_opt/1e9:.0f}B")
print(f"Chinchilla D*  : {d_opt/1e12:.0f}T tokens")
print(f"5× over-trained: N ~ {n_opt/5/1e9:.0f}B on D ~ {d_opt*5/1e12:.0f}T tokens")

Compare your answer to actual GPT-4 / GPT-5 disclosures. Order-of-magnitude reasoning from public compute is surprisingly accurate.

💡 Hint · If GPT-5 was trained on 25000 H100s for 90 days at 400 TFLOP/s BF16, what compute is that? What's the Chinchilla-optimal model size? What size do you expect them to actually pick if they follow LLaMA-3's over-train pattern (5-10× over Chinchilla)?

(d) Production reality · 15 min

War story DeepMind — the Chinchilla paper itself· 2022400+ trained models
🔥 What broke

DeepMind ran 400+ pretraining experiments across model sizes from 70M to 16B and dataset sizes from 5B to 500B tokens. The result contradicted OpenAI's Kaplan (2020) scaling laws.

Under Kaplan, GPT-3-scale compute (~3×10^23 FLOPs) should be spent on a 175B model with 300B tokens. Under Chinchilla, the same compute is optimally spent on a 70B model with 1.4T tokens.

🧯 The fix

DeepMind trained Chinchilla-70B on 1.4T tokens using GPT-3-comparable compute. It beat GPT-3 on nearly every benchmark despite being 40% the size. This validated the new scaling law and reset the industry.

🎓 Lesson to steal
Small errors in scaling-law exponents lead to catastrophically wrong training decisions. Every LLM lab now runs its own IsoFLOP sweeps before spending $50M on a big pretraining run.
Post-mortem
War story Meta AI · LLaMA-3· 202415T-token pretrain, tens of thousands of H100s
🔥 What broke

Chinchilla says LLaMA-3-8B should be trained on ~160B tokens. Meta trained it on 15T — nearly 100× the Chinchilla-optimal data. Naively, that's an enormous waste of pretraining compute.

🧯 The fix

They knew: pretraining is a one-time cost; inference is forever. An 8B model serves at a fraction of the cost of a 70B, so squeezing every drop of loss out of the small model — even at 100× training-compute penalty — pays back in weeks of production serving.

Result: LLaMA-3-8B matches LLaMA-2-70B on many benchmarks while being ~9× cheaper to serve.

🎓 Lesson to steal
Chinchilla-optimal minimises training-loss-per-training-FLOP. It doesn't account for inference. If your model will handle more than 10^13 tokens of inference (any consumer product), over-training the smaller model by 10-100× is almost always the right call.
War story Anthropic / OpenAI / Google — compute-limited trainingevery flagship LLM 2023–2026
🔥 What broke

Repeated pattern: a lab announces a compute budget (e.g. '10^25 FLOPs') and researchers immediately debate whether the model should be 400B params on 4T tokens or 100B on 15T. Getting this wrong wastes millions of GPU-hours.

🧯 The fix

Modern process: run a small (10^20–10^22 FLOPs) IsoFLOP sweep with the exact architecture + data mix planned. Fit the local scaling exponents. Extrapolate to the target budget. Choose N, D on the (slightly-over-Chinchilla) frontier — never on Chinchilla-optimal exactly, because inference matters.

🎓 Lesson to steal
Scaling laws are recipes for how to calibrate, not oracles. Every lab re-fits them for its own architecture + data because the exponents shift with tokenizer, data quality, and MoE vs dense.

Where this shows up next

Scaling laws underpin every training + inference decision
S115 · Efficient Attention
Flash-Attention reduces the constant hidden in the 6·N·D FLOPs formula. It moves the frontier without changing the exponents.
S123 · Fine-tuning + LoRA
Fine-tuning laws follow similar power-laws but with much smaller D. LoRA is the fine-tune analogue of over-training a small model.
S124 · LLM Serving
The 'why over-train small' argument turns into concrete cost-per-token math here.
S128 · Cost & Sustainability
Scaling laws + electricity prices give you a lifetime-cost model for choosing which LLM to deploy.
S130 · Model Selection
Chinchilla-adjusted comparison lets you compare 'value per FLOP' across GPT-4, Claude, Gemini, LLaMA.
S117 · RAG Chunking
Even embedding-model providers pick model size using the encoder version of these laws.

(e) Recall + stretch · 10 min

Quick recall · click to reveal
★ = stretch question

Explain-out-loud test

  1. What did Chinchilla change about how the industry trains LLMs?
  2. What is the '20 tokens per parameter' rule, and when should you deliberately violate it?
  3. Given a fixed GPU budget, what's the sequence of decisions to size a model?

What comes next

Hub: The 6-Month Learning Plan


Part of a 130-session evergreen learning series. Session structure: intuition → visual → hands-on → production war stories → recall. Duration: 90 minutes.