11.6  Scaling Laws

When pretraining a Transformer language model (Section 11.2), two macroscopic quantities determine the compute bill: the number of non-embedding parameters \(N\) in the \(L\) Transformer blocks, and the number of training tokens \(D\) streamed through the optimizer. Because each token requires a predictable number of floating-point operations (FLOPs) per parameter, a fixed training compute budget \(C\) (in FLOPs) forces a direct trade-off between model size \(N\) and data budget \(D\): should we train a larger model for fewer steps, or a smaller model on more tokens?

Empirical neural scaling laws (Kaplan et al. 2020) revealed that validation cross-entropy loss follows a smooth power-law surface \(\mathcal{L}(N, D)\) across orders of magnitude in \(N\) and \(D\). Hoffmann et al. (2022) then showed that minimizing loss at fixed pretraining compute \(C \approx 6 N D\) requires scaling model parameters \(N^*(C)\) and training tokens \(D^*(C)\) in equal proportion (\(N^* \propto C^{1/2}, D^* \propto C^{1/2}\), with roughly \(D^* / N^* \approx 20\) tokens per parameter, Figure 11.6.1). This section derives the parameter census \(N \approx 12 L d^2\) and the FLOP rule \(C \approx 6 N D\), verifies both against exact operator counters, runs a 15-model scaling grid across 5 sizes and 3 token budgets on WikiText-103, and explains why accounting for inference cost shifts modern open models toward training smaller models far past the Chinchilla ratio.

from torch.nn.attention import SDPBackend, sdpa_kernel
from torch.utils.flop_counter import FlopCounterMode

11.6.1 Counting Parameters (\(N \approx 12 L d^2\)) and FLOPs (\(C \approx 6 N D\))

11.6.1.1 Blocks vs. Embeddings

In a dense \(L\)-block GPT of hidden width \(d\) with standard multi-head attention (\(H_{\textrm{kv}} = H\)) and SwiGLU width \(d_{\textrm{ff}} = \operatorname{round}(\frac{8}{3}d)\) (Section 11.1):

  • Each attention sublayer holds four \(d \times d\) projection matrices (\(\mathbf{W}_q, \mathbf{W}_k, \mathbf{W}_v, \mathbf{W}_o\)): \(4 d^2\) parameters.

  • Each SwiGLU FFN holds three matrices (\(\mathbf{W}_g, \mathbf{W}_1 \in \mathbb{R}^{d \times \frac{8}{3}d}\) and \(\mathbf{W}_2 \in \mathbb{R}^{\frac{8}{3}d \times d}\)): \(8 d^2\) parameters.

  • Each block therefore holds \(12 d^2\) matrix parameters (plus \(2d\) RMSNorm gains), and \(L\) blocks hold

    \[N \;=\; 12 L d^2 \tag{11.6.1}\]

    non-embedding matrix parameters, while the tied token embedding table adds \(V d\) parameters:

gpt = d2l.GPT
def gpt(*args, **kwargs):  # Fresh random weights for every model
    return d2l.GPT(*args, **kwargs, rngs=nnx.Rngs(d2l.get_key()))

We verify that the non-embedding parameter count equals \(12 L d^2\) (to within the negligible \(O(Ld)\) normalization gains and biases) on both our 6-block byte-level GPT and 12-block GPT-2 Small:

def census(model):
    L, d = len(model.blks), model.num_hiddens
    emb = d2l.num_params(model.token_emb) + (
        d2l.num_params(model.pos_emb) if model.pos == 'learned' else 0)
    total = d2l.num_params(model)
    print(f'embedding {emb / 1e6:6.2f}M ({emb / total:5.1%}),  '
          f'blocks {(total - emb) / 1e6:6.2f}M '
          f'= {(total - emb) / (L * d ** 2):.2f} L d^2,  '
          f'total {total / 1e6:.2f}M')

census(gpt(256))
census(gpt(50257, num_hiddens=768, num_heads=12, num_blks=12,
           pos='learned', norm='layer', act='gelu', bias=True))
embedding   0.07M ( 1.4%),  blocks   4.72M = 12.01 L d^2,  total 4.79M
embedding  39.38M (31.6%),  blocks  85.06M = 12.02 L d^2,  total 124.44M
def census(model):
    L, d = len(model.blks), model.num_hiddens
    emb = d2l.num_params(model.token_emb) + (
        d2l.num_params(model.pos_emb) if model.pos == 'learned' else 0)
    total = d2l.num_params(model)
    print(f'embedding {emb / 1e6:6.2f}M ({emb / total:5.1%}),  '
          f'blocks {(total - emb) / 1e6:6.2f}M '
          f'= {(total - emb) / (L * d ** 2):.2f} L d^2,  '
          f'total {total / 1e6:.2f}M')

census(gpt(256))
census(gpt(50257, num_hiddens=768, num_heads=12, num_blks=12,
           pos='learned', norm='layer', act='gelu', bias=True))
embedding   0.07M ( 1.4%),  blocks   4.72M = 12.01 L d^2,  total 4.79M
embedding  39.38M (31.6%),  blocks  85.06M = 12.02 L d^2,  total 124.44M

11.6.1.2 Six FLOPs per Parameter and Token (\(C \approx 6 N D\))

Why does one training token consume approximately \(6 N\) FLOPs across the \(N = 12 L d^2\) linear-projection parameters?

  1. Forward pass (\(2 N\) FLOPs/token): Multiplying a token vector \(\mathbf{x} \in \mathbb{R}^{d_{\textrm{in}}}\) by a weight matrix \(\mathbf{W} \in \mathbb{R}^{d_{\textrm{in}} \times d_{\textrm{out}}}\) performs \(d_{\textrm{in}} d_{\textrm{out}}\) multiply–adds \(= 2 P\) FLOPs (where \(P = d_{\textrm{in}} d_{\textrm{out}}\) is the matrix’s parameter count). Summing over all \(N\) matrix parameters over \(D\) tokens gives \(2 N D\) forward FLOPs.
  2. Backward pass (\(4 N\) FLOPs/token): Backpropagating through \(\mathbf{Y} = \mathbf{X}\mathbf{W}\) requires two matrix multiplications of size \(P\) per token: \(\nabla_{\mathbf{X}}\mathcal{L} = (\nabla_{\mathbf{Y}}\mathcal{L})\mathbf{W}^\top\) (\(2P\) FLOPs) and \(\nabla_{\mathbf{W}}\mathcal{L} = \mathbf{X}^\top(\nabla_{\mathbf{Y}}\mathcal{L})\) (\(2P\) FLOPs), totaling \(4 N D\) backward FLOPs.

Adding the forward and backward passes gives the fundamental training compute approximation (Kaplan et al. 2020):

\[ C \;\approx\; 6 N D. \tag{11.6.2}\]

(Including the \(Q K^\top\) and \(A V\) attention score dot products over context window length \(T\) adds \(12 L T d D\) FLOPs, multiplying \(6 N D\) by \(1 + \frac{T}{6d}\), which is close to \(1\) whenever \(T \ll 6d\). An implementation that skips the masked half of a causal attention matrix halves the correction.)

11.6.1.3 Checking the Arithmetic Against Hardware Counters

We can verify Equation 11.6.2 directly against exact FLOP counts of the framework on a single training step of gpt(256, act='gelu'):

PyTorch’s FlopCounterMode counts the FLOPs of every operator.

XLA’s cost analysis counts the FLOPs of the compiled program on the CPU.

model = gpt(256, act='gelu')
X = torch.randint(0, 256, (64, 128))
Y = torch.randint(0, 256, (64, 128))
N = sum(p.numel() for p in model.parameters() if p.ndim == 2)
with sdpa_kernel(SDPBackend.MATH):  # Attention as visible matrix products
    with FlopCounterMode(display=False) as fwd:
        loss = F.cross_entropy(model(X).flatten(0, 1), Y.flatten())
    with FlopCounterMode(display=False) as bwd:
        loss.backward()
f, b = fwd.get_total_flops(), bwd.get_total_flops()
print(f'forward {f:.3e} FLOPs, {f / (2 * N * X.numel()):.3f} x 2ND')
print(f'step    {f + b:.3e} FLOPs, {(f + b) / (6 * N * X.numel()):.3f} x 6ND')
print(f'backward / forward = {b / f:.2f}')
forward 8.483e+10 FLOPs, 1.082 x 2ND
step    2.545e+11 FLOPs, 1.082 x 6ND
backward / forward = 2.00
model = gpt(256, act='gelu')
key_x, key_y = jax.random.split(d2l.get_key())
X = jax.random.randint(key_x, (64, 128), 0, 256)
Y = jax.random.randint(key_y, (64, 128), 0, 256)
graphdef, params, rest = nnx.split(model, nnx.Param, ...)
N = sum(p.size for p in jax.tree.leaves(params) if p.ndim == 2)
# Count on the CPU: on a GPU the count depends on the kernels XLA picks
params, rest, X, Y = jax.device_put((params, rest, X, Y), d2l.cpu())

def loss_fn(params, X, Y):
    logits = nnx.merge(graphdef, params, rest)(X)
    return optax.softmax_cross_entropy_with_integer_labels(
        logits.reshape(-1, logits.shape[-1]), Y.reshape(-1)).mean()

f = jax.jit(loss_fn).lower(params, X, Y).compile().cost_analysis()['flops']
s = jax.jit(jax.value_and_grad(loss_fn)).lower(
    params, X, Y).compile().cost_analysis()['flops']
print(f'forward {f:.3e} FLOPs, {f / (2 * N * X.size):.3f} x 2ND')
print(f'step    {s:.3e} FLOPs, {s / (6 * N * X.size):.3f} x 6ND')
print(f'backward / forward = {(s - f) / f:.2f}')
forward 8.575e+10 FLOPs, 1.094 x 2ND
step    2.625e+11 FLOPs, 1.116 x 6ND
backward / forward = 2.06

The measured backward pass is about twice the forward pass (\(2.0\text{--}2.1\times\)), and \(6 N D\) (with the tied output head and attention score term \(12 L T d D\) accounted for) matches the exact operator count to within a few percent.

11.6.2 A Miniature Scaling Study on WikiText-103

11.6.2.1 Five Model Sizes Across Three Data Budgets

To observe scaling behavior firsthand, we train a grid of 15 models on WikiText-103: five architectures spanning \(N \in [0.3\textrm{M}, 14\textrm{M}]\) non-embedding parameters ((d, L, H) from (96, 3, 4) up to (384, 8, 8)) crossed with three step budgets \(s \in \{500, 1000, 2000\}\) steps (corresponding to \(D \in \{4.10\textrm{M}, 8.19\textrm{M}, 16.38\textrm{M}\}\) training bytes):

data = d2l.WikiText103(batch_size=64, num_steps=128)
print(f'{len(data.train) / 1e6:.0f}M training bytes, '
      f'{len(data.val) / 1e6:.2f}M validation bytes, '
      f'vocabulary of {len(data.vocab)}')
270M training bytes, 1.14M validation bytes, vocabulary of 256
data = d2l.WikiText103(batch_size=64, num_steps=128)
print(f'{len(data.train) / 1e6:.0f}M training bytes, '
      f'{len(data.val) / 1e6:.2f}M validation bytes, '
      f'vocabulary of {len(data.vocab)}')
270M training bytes, 1.14M validation bytes, vocabulary of 256

With the corpus loaded, we train all \(5 \times 3 = 15\) (size, budget) configurations using width-scaled peak learning rates \(\eta = 2 \times 10^{-3} \cdot (256 / d)\) and record each model’s non-embedding parameter count Ns and validation cross-entropy val:

sizes = ((96, 3, 4), (128, 3, 4), (192, 4, 6), (256, 6, 8), (384, 8, 8))
budgets = (500, 1000, 2000)  # Steps of 64 windows of 128 bytes
Ns, train, val = [], [], {num_steps: [] for num_steps in budgets}
for d, num_blks, num_heads in sizes:
    for num_steps in budgets:
        model = gpt(len(data.vocab), num_hiddens=d, num_heads=num_heads,
                    num_blks=num_blks)
        optimizer = d2l.LMOptimizer(model, lr=2e-3 * 256 / d,
                                    num_steps=num_steps,
                                    warmup=max(100, num_steps // 10))
        losses = d2l.train_steps(model, data, optimizer, num_steps)
        val[num_steps].append(
            math.log(d2l.lm_perplexity(model, data.val_dataloader())))
    # The size of the models just trained, and the training loss of the
    # longest of their runs
    Ns.append(d2l.num_params(model) - d2l.num_params(model.token_emb))
    train.append(sum(losses[-50:]) / 50)
    print(f'd = {d:3d}, {num_blks} blocks, N = {Ns[-1] / 1e6:5.2f}M: '
          'validation ' + ' / '.join(f'{val[s][-1]:.2f}' for s in budgets)
          + f', training {train[-1]:.2f}')
d =  96, 3 blocks, N =  0.33M: validation 1.63 / 1.49 / 1.38, training 1.41
d = 128, 3 blocks, N =  0.59M: validation 1.58 / 1.45 / 1.34, training 1.37
d = 192, 4 blocks, N =  1.77M: validation 1.49 / 1.38 / 1.29, training 1.31
d = 256, 6 blocks, N =  4.72M: validation 1.46 / 1.34 / 1.25, training 1.27
d = 384, 8 blocks, N = 14.16M: validation 1.42 / 1.31 / 1.22, training 1.24
sizes = ((96, 3, 4), (128, 3, 4), (192, 4, 6), (256, 6, 8), (384, 8, 8))
budgets = (500, 1000, 2000)  # Steps of 64 windows of 128 bytes
Ns, train, val = [], [], {num_steps: [] for num_steps in budgets}
for d, num_blks, num_heads in sizes:
    for num_steps in budgets:
        model = gpt(len(data.vocab), num_hiddens=d, num_heads=num_heads,
                    num_blks=num_blks)
        optimizer = d2l.LMOptimizer(model, lr=2e-3 * 256 / d,
                                    num_steps=num_steps,
                                    warmup=max(100, num_steps // 10))
        losses = d2l.train_steps(model, data, optimizer, num_steps)
        val[num_steps].append(
            math.log(d2l.lm_perplexity(model, data.val_dataloader())))
    # The size of the models just trained, and the training loss of the
    # longest of their runs
    Ns.append(d2l.num_params(model) - d2l.num_params(model.token_emb))
    train.append(sum(losses[-50:]) / 50)
    print(f'd = {d:3d}, {num_blks} blocks, N = {Ns[-1] / 1e6:5.2f}M: '
          'validation ' + ' / '.join(f'{val[s][-1]:.2f}' for s in budgets)
          + f', training {train[-1]:.2f}')
d =  96, 3 blocks, N =  0.33M: validation 1.65 / 1.49 / 1.38, training 1.39
d = 128, 3 blocks, N =  0.59M: validation 1.58 / 1.45 / 1.35, training 1.37
d = 192, 4 blocks, N =  1.77M: validation 1.50 / 1.38 / 1.29, training 1.30
d = 256, 6 blocks, N =  4.72M: validation 1.46 / 1.34 / 1.25, training 1.27
d = 384, 8 blocks, N = 14.16M: validation 1.42 / 1.32 / 1.22, training 1.23

11.6.2.2 Loss Against Model Size, Data Budget, and Compute

Plotting validation cross-entropy against non-embedding parameters \(N\) on a log axis for each token budget \(D\), and against total training compute \(C = 6 N D\):

tokens = {s: s * 64 * 128 for s in budgets}  # Tokens read in s steps
d2l.plot(Ns, [val[s] for s in budgets], 'non-embedding parameters N',
         'validation loss (nats)',
         legend=[f'D = {tokens[s] / 1e6:.1f}M' for s in budgets],
         xscale='log', yscale='log', fmts=('C0o-', 'C1s-', 'C2^-'),
         legend_loc='outside')

tokens = {s: s * 64 * 128 for s in budgets}  # Tokens read in s steps
d2l.plot(Ns, [val[s] for s in budgets], 'non-embedding parameters N',
         'validation loss (nats)',
         legend=[f'D = {tokens[s] / 1e6:.1f}M' for s in budgets],
         xscale='log', yscale='log', fmts=('C0o-', 'C1s-', 'C2^-'),
         legend_loc='outside')

Re-plotting the same 15 validation losses against total training compute \(C = 6 N D\) (and printing three runs of similar compute, \(C \approx 2\text{--}3 \times 10^{14}\textrm{ FLOPs}\) and within \(2\times\) of each other) reveals how the compute-optimal model size shifts upward as the FLOP budget grows:

d2l.plot([[6 * N * tokens[s] for s in budgets] for N in Ns],
         [[val[s][i] for s in budgets] for i in range(len(Ns))],
         'training compute C = 6ND (FLOPs)', 'validation loss (nats)',
         legend=[f'N = {N / 1e6:.2f}M' for N in Ns], xscale='log',
         fmts=('C0o-', 'C1s-', 'C2^-', 'C3v-', 'C4D-'), legend_loc='outside')
for i, s in ((2, 2000), (3, 1000), (4, 500)):  # Larger N, fewer tokens
    print(f'N = {Ns[i] / 1e6:5.2f}M, D = {tokens[s] / 1e6:4.1f}M tokens: '
          f'C = {6 * Ns[i] * tokens[s]:.1e} FLOPs, '
          f'validation {val[s][i]:.2f}')
N =  1.77M, D = 16.4M tokens: C = 1.7e+14 FLOPs, validation 1.29
N =  4.72M, D =  8.2M tokens: C = 2.3e+14 FLOPs, validation 1.34
N = 14.16M, D =  4.1M tokens: C = 3.5e+14 FLOPs, validation 1.42

d2l.plot([[6 * N * tokens[s] for s in budgets] for N in Ns],
         [[val[s][i] for s in budgets] for i in range(len(Ns))],
         'training compute C = 6ND (FLOPs)', 'validation loss (nats)',
         legend=[f'N = {N / 1e6:.2f}M' for N in Ns], xscale='log',
         fmts=('C0o-', 'C1s-', 'C2^-', 'C3v-', 'C4D-'), legend_loc='outside')
for i, s in ((2, 2000), (3, 1000), (4, 500)):  # Larger N, fewer tokens
    print(f'N = {Ns[i] / 1e6:5.2f}M, D = {tokens[s] / 1e6:4.1f}M tokens: '
          f'C = {6 * Ns[i] * tokens[s]:.1e} FLOPs, '
          f'validation {val[s][i]:.2f}')
N =  1.77M, D = 16.4M tokens: C = 1.7e+14 FLOPs, validation 1.29
N =  4.72M, D =  8.2M tokens: C = 2.3e+14 FLOPs, validation 1.34
N = 14.16M, D =  4.1M tokens: C = 3.5e+14 FLOPs, validation 1.42

Two patterns stand out:

  1. At the largest token budget (\(2{,}000\) steps, \(D = 16.4\textrm{M}\) bytes), validation loss decreases almost linearly with \(\log N\) across the small and medium models before bending flat at the largest model (\(N = 14.16\textrm{M}\)), where \(2{,}000\) steps (\(D/N \approx 1.2\) bytes per parameter) is still starved of data relative to \(14\textrm{M}\) parameters.
  2. When all 15 runs are plotted against total training FLOPs \(C = 6 N D\), their lower envelope traces the Pareto-optimal compute frontier: at low compute, small models win; at higher compute, larger models overtake them once given enough steps.

11.6.3 Compute-Optimal Allocation (Chinchilla Scaling)

11.6.3.1 The Chinchilla Parametric Law

Hoffmann et al. (2022) (and the refit of Besiroglu et al. (2024)) model the validation loss surface \(\mathcal{L}(N, D)\) as the sum of an irreducible text-entropy floor \(L_\infty\) and two power-law penalties in \(N\) and \(D\):

\[ \mathcal{L}(N, D) \;=\; L_\infty \;+\; \frac{A}{N^\alpha} \;+\; \frac{B}{D^\beta}. \tag{11.6.3}\]

11.6.3.2 The Compute-Optimal Split (\(N^*(C)\) and \(D^*(C)\))

Minimizing Equation 11.6.3 with respect to \(N\) and \(D\) subject to \(C = 6 N D\) (substituting \(D = C / (6N)\) and setting \(\partial \mathcal{L} / \partial N = 0\)) yields power-law scaling for both the optimal model size \(N^*(C)\) and optimal token budget \(D^*(C)\):

\[ N^*(C) \;=\; G \left(\frac{C}{6}\right)^a, \qquad D^*(C) \;=\; G^{-1} \left(\frac{C}{6}\right)^b, \tag{11.6.4}\]

where

\[ \begin{aligned} a &\;=\; \frac{\beta}{\alpha + \beta}, \qquad b \;=\; \frac{\alpha}{\alpha + \beta}, \\ G &\;=\; \left(\frac{\alpha A}{\beta B}\right)^{\frac{1}{\alpha + \beta}}. \end{aligned} \tag{11.6.5}\]

Figure 11.6.1: Loss contours of the Chinchilla law with the refit constants of Besiroglu et al. (2024), introduced below, over parameters and training tokens. Dashed: budgets of equal compute \(C = 6ND\); dots: the compute-optimal model of each budget; orange: the compute-optimal path. Chinchilla’s square sits on the optimum of its budget, covering its dot; Llama 3 8B, on a budget close to Chinchilla’s, lies far from the path at a tenth of the optimal size.

Because \(\alpha \approx \beta \approx 0.34\text{--}0.37\), the exponents satisfy \(a \approx b \approx 0.5\): when training compute \(C\) increases by \(100\times\), both model size \(N^*\) and training tokens \(D^*\) increase by \(\sim 10\times\), keeping the compute-optimal ratio \(D^* / N^* \approx 20\) tokens per parameter roughly constant.

This was not the first answer to the question. Two years earlier, Kaplan et al. (2020) had fitted power laws of the same kind and concluded that most of any extra compute should go into the model: \(N^* \propto C^{0.73}\), which leaves only \(D^* \propto C^{0.27}\) for data (Figure 11.6.2). The two studies disagree mainly because of the learning-rate schedule. Kaplan et al. used one schedule for all runs and read the losses of smaller token budgets off intermediate checkpoints, where the learning rate had not yet decayed. This makes training on fewer tokens look worse than it is, so data appears to help less than it does. Their models were also small, at most \(1.5\textrm{B}\) parameters. Hoffmann et al. trained models of up to \(16\textrm{B}\) parameters and matched the cosine schedule to the length of each run. Our grid above did the same, which is why each of its 15 runs has a cosine horizon of its own (Exercise 3 measures what happens otherwise).

Figure 11.6.2: Compute-optimal model size against training compute under the two published exponents, \(0.73\) (Kaplan et al.) and \(0.5\) (Hoffmann et al.). Both lines are drawn through the same model at \(10^{18}\) FLOPs, and only their slopes come from the papers. A \(100\times\) larger budget calls for a \(29\times\) larger model under the first exponent and a \(10\times\) larger one under the second. The square marks Chinchilla.

The function optimum below evaluates Equation 11.6.4 at the training budget of Chinchilla, \(C = 5.76 \times 10^{23}\) FLOPs, once with the constants published by Hoffmann et al. and once with the refit of Besiroglu et al.:

fits = {'Hoffmann et al.': (1.69, 406.4, 410.7, 0.34, 0.28),
        'Besiroglu et al.': (1.82, 482.0, 2085.4, 0.348, 0.366)}

def optimum(C, L_inf, A, B, alpha, beta):
    G = (alpha * A / (beta * B)) ** (1 / (alpha + beta))
    N = G * (C / 6) ** (beta / (alpha + beta))
    return N, C / (6 * N)

for name, fit in fits.items():
    N, D = optimum(5.76e23, *fit)
    print(f'{name:17s} N* = {N / 1e9:3.0f}B, D* = {D / 1e12:.2f}T, '
          f'{D / N:3.0f} tokens per parameter')
Hoffmann et al.   N* =  32B, D* = 2.98T,  93 tokens per parameter
Besiroglu et al.  N* =  72B, D* = 1.33T,  18 tokens per parameter
fits = {'Hoffmann et al.': (1.69, 406.4, 410.7, 0.34, 0.28),
        'Besiroglu et al.': (1.82, 482.0, 2085.4, 0.348, 0.366)}

def optimum(C, L_inf, A, B, alpha, beta):
    G = (alpha * A / (beta * B)) ** (1 / (alpha + beta))
    N = G * (C / 6) ** (beta / (alpha + beta))
    return N, C / (6 * N)

for name, fit in fits.items():
    N, D = optimum(5.76e23, *fit)
    print(f'{name:17s} N* = {N / 1e9:3.0f}B, D* = {D / 1e12:.2f}T, '
          f'{D / N:3.0f} tokens per parameter')
Hoffmann et al.   N* =  32B, D* = 2.98T,  93 tokens per parameter
Besiroglu et al.  N* =  72B, D* = 1.33T,  18 tokens per parameter

11.6.3.3 Training Past the Chinchilla Optimum for Inference

Why did Llama 3 8B (Figure 11.6.1) train an 8B-parameter model on \(15\textrm{T}\) tokens (\(D / N \approx 1{,}875\) tokens per parameter, nearly \(100\times\) the Chinchilla ratio) instead of training a Chinchilla-optimal \(70\textrm{B}\) model on \(1.4\textrm{T}\) tokens at the same pretraining compute \(C \approx 7 \times 10^{23}\) FLOPs?

Because Chinchilla minimizes pretraining FLOPs \(6 N D\) alone, ignoring the \(2 N D_{\textrm{inf}}\) inference FLOPs and KV-cache memory spent serving the model after deployment (Sardana et al. 2024). Traveling along a constant-loss contour \(\mathcal{L}(N, D) = \mathcal{L}_{\textrm{target}}\) shows that an 8B model over-trained on \(15\textrm{T}\) tokens reaches a loss close to a Chinchilla-allocated \(30\textrm{B}\text{--}40\textrm{B}\) model while making every subsequent inference token \(4\text{--}5\times\) cheaper to serve:

L_inf, A, B, alpha, beta = fits['Besiroglu et al.']
loss = lambda N, D: L_inf + A / N ** alpha + B / D ** beta
reported = {'Chinchilla': (70e9, 1.4e12), 'Llama 3 8B': (8e9, 15e12),
            'Llama 3 405B': (405e9, 15.6e12), 'OLMo 2 7B': (7e9, 4.05e12),
            'Gemma 3 27B': (27e9, 14e12)}
for name, (N, D) in reported.items():
    N_opt, D_opt = optimum(6 * N * D, L_inf, A, B, alpha, beta)
    print(f'{name:12s} {D / N:5.0f} tokens per parameter, '
          f'{N / N_opt:4.2f} x optimal size, '
          f'loss +{loss(N, D) - loss(N_opt, D_opt):.3f}')
Chinchilla      20 tokens per parameter, 0.96 x optimal size, loss +0.000
Llama 3 8B    1875 tokens per parameter, 0.10 x optimal size, loss +0.054
Llama 3 405B    39 tokens per parameter, 0.65 x optimal size, loss +0.001
OLMo 2 7B      579 tokens per parameter, 0.18 x optimal size, loss +0.037
Gemma 3 27B    519 tokens per parameter, 0.18 x optimal size, loss +0.023
L_inf, A, B, alpha, beta = fits['Besiroglu et al.']
loss = lambda N, D: L_inf + A / N ** alpha + B / D ** beta
reported = {'Chinchilla': (70e9, 1.4e12), 'Llama 3 8B': (8e9, 15e12),
            'Llama 3 405B': (405e9, 15.6e12), 'OLMo 2 7B': (7e9, 4.05e12),
            'Gemma 3 27B': (27e9, 14e12)}
for name, (N, D) in reported.items():
    N_opt, D_opt = optimum(6 * N * D, L_inf, A, B, alpha, beta)
    print(f'{name:12s} {D / N:5.0f} tokens per parameter, '
          f'{N / N_opt:4.2f} x optimal size, '
          f'loss +{loss(N, D) - loss(N_opt, D_opt):.3f}')
Chinchilla      20 tokens per parameter, 0.96 x optimal size, loss +0.000
Llama 3 8B    1875 tokens per parameter, 0.10 x optimal size, loss +0.054
Llama 3 405B    39 tokens per parameter, 0.65 x optimal size, loss +0.001
OLMo 2 7B      579 tokens per parameter, 0.18 x optimal size, loss +0.037
Gemma 3 27B    519 tokens per parameter, 0.18 x optimal size, loss +0.023

11.6.4 Summary

A dense \(L\)-layer Transformer of width \(d\) with SwiGLU (\(d_{\textrm{ff}} \approx \frac{8}{3}d\)) contains \(N \approx 12 L d^2\) non-embedding matrix parameters (\(4 L d^2\) in attention and \(8 L d^2\) in the FFN) and consumes \(C \approx 6 N D\) training FLOPs over \(D\) tokens (\(2 N D\) forward and \(4 N D\) backward, Equation 11.6.2). Under the Chinchilla scaling law \(\mathcal{L}(N, D) = L_\infty + A N^{-\alpha} + B D^{-\beta}\) (Equation 11.6.3), minimizing validation loss at fixed pretraining compute \(C = 6 N D\) scales parameters and tokens with exponents \(a = \beta/(\alpha+\beta) \approx 0.5\) and \(b = \alpha/(\alpha+\beta) \approx 0.5\) (Equation 11.6.4–Equation 11.6.5), yielding roughly \(D^* / N^* \approx 20\) tokens per parameter. Accounting for lifetime inference compute (\(2 N D_{\textrm{inf}}\)) and serving latency shifts the total-compute optimum along the constant-loss contour toward smaller models \(N\) over-trained on hundreds or thousands of tokens per parameter.

11.6.5 Exercises

  1. Attention-score FLOP correction (\(1 + T / (6d)\)). Equation Equation 11.6.2 omits the attention score/value products \(\mathbf{Q}\mathbf{K}^\top\) and \(\mathbf{A}\mathbf{V}\), and the output head \(\mathbf{H}^{(L)}\mathbf{E}^\top\).

    1. Show that in an \(L\)-block model of width \(d\) and window length \(T\), the forward attention dot products perform \(4 L T^2 d\) FLOPs per window (\(4 L T d\) FLOPs per token), and forward + backward attention dot products perform \(12 L T d\) FLOPs per token (or \(6 L T d\) when causal symmetry is exploited by FlashAttention).
    2. Take the ratio of \(6 L T d\) to \(6 N = 72 L d^2\) to show that causal attention adds a relative FLOP fraction of \(T / (12 d)\) (or \(T / (6 d)\) without causal tile skipping). At what context length \(T^*\) does attention match the linear-projection FLOPs of Llama 3 8B (\(d = 4096\))?
  2. Total vs. non-embedding parameters in the scaling grid. Each model in our 5-size WikiText-103 sweep used a byte vocabulary (\(V = 256\)), where \(V d\) is at most about \(7\%\) of \(12 L d^2\). Repeat census for the same five (d, L, H) backbones if they instead used a BPE vocabulary of \(V = 128{,}256\) tokens (Llama 3). What fraction of total parameters would the embedding table represent in the smallest (d=96, L=3) versus largest (d=384, L=8) model, and why do Kaplan et al. (2020) fit power laws against \(N_{\textrm{non-emb}} = 12 L d^2\) rather than \(N_{\textrm{total}}\)?

  3. Cosine decay horizon vs. fixed step horizon. In our 15-run scaling study, each budget \(s \in \{500, 1000, 2000\}\) ran a cosine schedule of its own, which decays the learning rate to zero at step \(s\) (matching the schedule to the length of the run was the crucial correction of Hoffmann et al. (2022) to Kaplan et al. (2020)). Re-run the three budgets for the medium model (192, 4, 6) using a single fixed cosine horizon num_steps=2000 inside LMOptimizer and merely reading off the validation loss at steps 500, 1000, and 2000. By how much does failing to decay the learning rate at \(s = 500\) and \(s = 1000\) overestimate the loss of short runs?

  4. Fitting the Chinchilla law to our 15-point grid. Using scipy.optimize.minimize (or grid search + nonlinear least squares), fit the parameters \((L_\infty, A, B, \alpha, \beta)\) of Equation 11.6.3 to the 15 (N, D, val_loss) points measured in our WikiText-103 sweep. What scaling exponents \(a = \beta/(\alpha+\beta)\) and \(b = \alpha/(\alpha+\beta)\) does the byte-level 15-point grid produce?

  5. Lifetime compute optimization with inference demand \(D_{\textrm{inf}}\). A model of size \(N\) trained on \(D\) tokens and deployed to serve \(D_{\textrm{inf}}\) inference tokens consumes total lifetime FLOPs \(C_{\textrm{tot}}(N, D) = 6 N D + 2 N D_{\textrm{inf}}\).

    1. Using Lagrange multipliers on \(\mathcal{L}(N, D) = L_\infty + A N^{-\alpha} + B D^{-\beta} = \mathcal{L}_{\textrm{target}}\), show that at the lifetime-compute minimum \((N^*, D^*)\), the marginal ratio satisfies

      \[\frac{\beta B (D^*)^{-\beta}}{\alpha A (N^*)^{-\alpha}} \;=\; \frac{6 N^* D^*}{6 N^* D^* + 2 N^* D_{\textrm{inf}}} \;=\; \frac{1}{1 + \frac{D_{\textrm{inf}}}{3 D^*}}.\]

    2. Verify that when \(D_{\textrm{inf}} = 0\) this recovers the Chinchilla balance \(\alpha A (N^*)^{-\alpha} = \beta B (D^*)^{-\beta}\), and solve numerically for \((N^*, D^*)\) at \(\mathcal{L}_{\textrm{target}} = \mathcal{L}(70\textrm{B}, 1.4\textrm{T})\) when \(D_{\textrm{inf}} \in \{10\textrm{T}, 100\textrm{T}, 500\textrm{T}\}\) tokens.

  6. Activation checkpointing and the \(8 N D\) rule. Full block-level activation checkpointing saves only the input \(\mathbf{X}^{(\ell-1)}\) to each block during the forward pass (\(2 N D\) FLOPs) and recomputes each block’s forward pass once during backpropagation before computing the backward matrix products (\(4 N D\) FLOPs). Show that activation checkpointing changes the pretraining compute formula from \(C \approx 6 N D\) to \(C \approx 8 N D\), and find how replacing \(6\) with \(8\) in Equation 11.6.4 scales \(N^*(C)\) and \(D^*(C)\) at fixed FLOP budget \(C\).

Discussions