Module contents
Stage 5 of 8Research 110 min

Second approach: isoFLOP profiles

Fit isoFLOP profiles and propagate uncertainty into compute-optimal allocation.

After this lesson you can

  • Run the isoFLOP profiles planned in the preregistration.
  • Fit a parabola per profile and estimate its minimum with uncertainty.
  • Fit power laws for optimal size and tokens against compute.
  • Compare with the first approach and the paper.

Before you start

A question that fits on a curve

You have a fixed compute budget CC. Spending more on parameters leaves fewer tokens; spending less allows longer training. Hoffmann and colleagues’ first approach answered by looking at the envelope of many training curves. The second, studied here, asks the question literally: fix CC, train several sizes with exactly the tokens exhausting that budget and see which finishes with the lowest loss.

In the Chinchilla paper, section 3.2, the experiment is repeated for nine budgets between 6⋅10186\cdot10^{18} and 3⋅10213\cdot10^{21} FLOPs, with models up to 16 000 million parameters. For each budget smoothed final loss is plotted against parameter count and a clear valley appears: there is an optimal size. A parabola is fitted to each valley, its minimum read, and the nine minima used to fit Nopt∝CaN_{\text{opt}}\propto C^{a} and Dopt∝CbD_{\text{opt}}\propto C^{b}. Table 2 gives a=0.49a=0.49 and b=0.51b=0.51.

The interactive contains two sets of profiles. The first is the 105 actual lab runs from this lesson. The second reproduces Chinchilla scale with the loss surface refitted by Besiroglu and colleagues from the paper’s data. Remove points and observe two things: how much the profile vertex moves and how much the law’s exponent, which uses all five vertices, moves.

InteractiveisoFLOP profiles: from valley to exponent
Interior minimum: the parabola has points on both sides of its vertex.

Measured profile with C = 2e11 = 2.0e11 FLOPs

Allocation law from the vertices of all 5 profiles

  • Mean across seeds (click to toggle)
  • Individual seeds
  • Parabola and vertex
  • Fit using all points
  • Current N* ∝ C^a law

Each blue point averages three independent lab runs. Gray points show individual seeds. The minimum achievable source loss is 2.2497 nats.

Data
Budget
Grid for this profile
N* for this profile17.3 k
Change versus all points+0.0 %
Optimal tokens per parameter111.2
Exponent a (all profiles)0.397
b = 1 - a0.603
a with full grids0.397
Left: final loss versus log₁₀ N for one budget, with the parabola fitted to retained points (gray dashed uses all). Right: log₁₀ N* versus log₁₀ C for five profiles and the line whose slope is exponent a. A vertex outside retained sizes is rejected and the law is no longer identified.

With “Left only” the parabola still has a vertex, but it falls outside its supporting points: the number exists and means nothing. With “Without endpoints,” by contrast, the vertex moves little because central points already fix curvature and position. At Chinchilla scale there is no noise and even so “Without endpoints” shifts the vertex 0.2 %: the true profile is not a parabola, and the fit’s measurement depends on the window. The next two sections turn these observations into formulas.

Definition and why the valley is nearly a parabola

Two definition details are essential. “Final” means the last point of a run whose rate schedule ends at that budget: Hoffmann shows that if the cosine cycle exceeds actual steps by more than 25 % performance visibly worsens, so an intermediate point from a long run is not a profile point. All points within and across profiles must share corpus, tokenizer, architecture, parameter convention and metric: the profile compares allocations, not pipelines.

To understand the valley’s shape use the parametric surface L(N,D)=E+AN−α+BD−βL(N,D)=E+A N^{-\alpha}+B D^{-\beta} (the third approach, studied next lesson). In variable x=ln⁡Nx=\ln N the profile is

ℓC(x)=E+Ae−αx+B(6C)βeβx.\ell_C(x) = E + A e^{-\alpha x} + B\left(\tfrac{6}{C}\right)^{\beta} e^{\beta x}.

The first term decreases and the second increases: more parameters reduce capacity error and increase data error. Setting the derivative to zero, αAe−αx=βB(6/C)βeβx\alpha A e^{-\alpha x} = \beta B (6/C)^\beta e^{\beta x}, gives

N∗(C)=G(C6)βα+β,G=(αAβB)1α+β,N^\ast(C) = G\left(\frac{C}{6}\right)^{\frac{\beta}{\alpha+\beta}},\qquad G=\left(\frac{\alpha A}{\beta B}\right)^{\frac{1}{\alpha+\beta}},

which is Hoffmann’s equation (4). The size exponent is a=β/(α+β)a=\beta/(\alpha+\beta) and, since D∗=C/(6N∗)D^\ast=C/(6N^\ast), the data exponent is b=1−ab=1-a. Using Besiroglu’s refitted values (α=0.3478\alpha=0.3478, β=0.3658\beta=0.3658) gives a=0.513a=0.513.

Call the two terms at the optimum u=Ae−αx∗u=Ae^{-\alpha x^\ast} and v=B(6/C)βeβx∗v=B(6/C)^\beta e^{\beta x^\ast}; the minimum condition is βv=αu\beta v=\alpha u. Second and third derivatives at x∗x^\ast are

κ=ℓC′′(x∗)=α2u+β2v=αu(α+β),τ=ℓC′′′(x∗)=−α3u+β3v=αu(α+β)(β−α).\kappa=\ell_C''(x^\ast)=\alpha^2u+\beta^2v=\alpha u(\alpha+\beta),\qquad \tau=\ell_C'''(x^\ast)=-\alpha^3u+\beta^3v=\alpha u(\alpha+\beta)(\beta-\alpha).

The ratio τ/κ=β−α\tau/\kappa=\beta-\alpha does not depend on CC. If α≈β\alpha\approx\beta, as in Besiroglu’s refit, the valley in ln⁡N\ln N is nearly symmetric and a parabola describes it well; if α\alpha and β\beta differ, the valley is asymmetric and the parabola is only its second-order Taylor approximation. This justifies fitting in ln⁡N\ln N rather than NN: in NN a power-law valley is much more asymmetric.

Choose sizes around the predicted optimum

For each budget choose six to eight sizes before training. If a prior rule predicts D=rND=rN, with C=6NDC=6ND the predicted center is

N0(C)=C6r,Nj=N0 ezj,N_0(C)=\sqrt{\frac{C}{6r}},\qquad N_j = N_0\,e^{z_j},

with offsets zjz_j symmetric around zero. In the lab, a pilot at 101110^{11} FLOPs placed the optimum near r=100r=100 tokens per parameter, and the registered grid is z∈{−1.2,−0.8,…,1.2}z\in\{-1.2,-0.8,\dots,1.2\}: seven sizes spanning factor e2.4≈11e^{2.4}\approx11. With r=100r=100 and C=1011C=10^{11} the center is N0=1011/600≈12 910N_0=\sqrt{10^{11}/600}\approx12\,910 parameters. Each size receives Dj=⌊C/(6Nj)⌋D_j=\lfloor C/(6N_j)\rfloor tokens rounded to whole batches, and enough updates are checked (the lab requires at least 50; shortest runs have 133).

Why center? The obvious reason is avoiding extrapolation: with all sizes on one side of the minimum, the imposed shape invents the parabola’s vertex. But there are two additional quantitative reasons in the following result.

Proof

By symmetry, ∑zj=∑zj3=0\sum z_j=\sum z_j^3=0, so column zz of the design matrix is orthogonal to columns 11 and z2z^2. The fit decomposes: the linear coefficient is c^1=∑zjyj/∑zj2\hat c_1=\sum z_jy_j/\sum z_j^2 and coefficients c^0,c^2\hat c_0,\hat c_2 come from projection onto {1,z2}\{1,z^2\}.

(1) Without noise, even terms ℓ∗\ell^\ast and κ2z2\tfrac\kappa2 z^2 are reproduced exactly: c^2=κ/2\hat c_2=\kappa/2. The cubic term is odd, orthogonal to 11 and z2z^2, and its projection onto zz has coefficient τ6∑zj4/∑zj2=τ6 m4/m2\tfrac\tau6\sum z_j^4/\sum z_j^2=\tfrac\tau6\,m_4/m_2. The vertex of c^2z2+c^1z+c^0\hat c_2z^2+\hat c_1z+\hat c_0 is at z=−c^1/(2c^2)=−τκm46m2z=-\hat c_1/(2\hat c_2)=-\tfrac{\tau}{\kappa}\tfrac{m_4}{6m_2}.

(2) Noise adds ∑zjεj/∑zj2\sum z_j\varepsilon_j/\sum z_j^2 to c^1\hat c_1, with variance σ2/∑zj2=σ2/(nm2)\sigma^2/\sum z_j^2=\sigma^2/(nm_2). The vertex is g(c^1,c^2)=−c^1/(2c^2)g(\hat c_1,\hat c_2)=-\hat c_1/(2\hat c_2), with ∂g/∂c1=−1/(2c2)=−1/κ\partial g/\partial c_1=-1/(2c_2)=-1/\kappa and ∂g/∂c2=c1/(2c22)\partial g/\partial c_2=c_1/(2c_2^2), which vanishes to first order because c1≈0c_1\approx0 near the center. By the delta method, Var⁡(x^∗)≈σ2/(κ2nm2)\operatorname{Var}(\hat x^\ast)\approx\sigma^2/(\kappa^2nm_2).

∎

Consequences are concrete. For the lab grid m2=0.64m_2=0.64 and m4=0.7168m_4=0.7168, so m4/(6m2)=0.187m_4/(6m_2)=0.187. In the parametric profile, τ/κ=β−α\tau/\kappa=\beta-\alpha: with Hoffmann’s published rounded values (α=0.34\alpha=0.34, β=0.28\beta=0.28) the vertex is biased by +0.011+0.011 in ln⁡N\ln N (1.1 % in NN); with Besiroglu’s, by −0.003-0.003. We checked by fitting parabolas to the exact surface: numerical bias matches the formula at all five figures. Since τ/κ\tau/\kappa does not depend on CC, bias is the same at every budget if the grid is equally centered everywhere: it shifts the law’s constant, not exponent.

If the grid is off-center, symmetry breaks and fourth-order terms begin to matter: with Besiroglu’s surface and a grid shifted by factor ee (zj+1z_j+1), bias changes from −0.003-0.003 to +0.038+0.038. If offset varies with CC because the prediction used a wrong exponent, bias changes across budgets and contaminates aa. The second result also says vertex standard error grows as 1/κ1/\kappa: a flat valley locates its minimum poorly, and widening the grid (larger m2m_2) locates it better at the cost of more shape bias. Grid width is a bias-variance trade-off.

Parabolic fit and vertex

In each profile, with xj=ln⁡Njx_j=\ln N_j and mean xˉ\bar x, fit by least squares

L(x)=c2(x−xˉ)2+c1(x−xˉ)+c0.L(x)=c_2(x-\bar x)^2+c_1(x-\bar x)+c_0 .

Centering on xˉ\bar x does not change the fit but greatly improves conditioning: with uncentered x≈10x\approx 10, columns x2x^2, xx and 11 are nearly collinear. If c2>0c_2>0, completing the square gives the vertex:

Proof

c2z2+c1z+c0=c2(z+c12c2)2+c0−c124c2c_2z^2+c_1z+c_0=c_2\big(z+\tfrac{c_1}{2c_2}\big)^2+c_0-\tfrac{c_1^2}{4c_2} with z=x−xˉz=x-\bar x. Since c2>0c_2>0, the square is minimal, and zero, only at z=−c1/(2c2)z=-c_1/(2c_2). Thus x∗=xˉ−c1/(2c2)x^\ast=\bar x-c_1/(2c_2) and N∗=ex∗N^\ast=e^{x^\ast}, because the exponential is strictly increasing. If c2≤0c_2\le0 the parabola has no minimum: it is the one-variable quadratic form, and its sign decides.

∎

The lab acceptance rule has four conditions, in this order: at least three distinct sizes, rank-3 design matrix, curvature c2>0c_2>0 and vertex strictly between the smallest and largest observed ln⁡Nj\ln N_j. The first three are algebraic; the fourth prevents publishing an extrapolated minimum. None guarantees that a parabola is a good model: inspect residuals for that. For each profile the lab prints root mean squared residual divided by standard error of seed means; a ratio near 1 says the parabola explains points to noise level, and a much larger one indicates asymmetric curvature or anomalous runs.

Using log⁡10N\log_{10}N instead of ln⁡N\ln N changes coefficients but gives the same vertex in size, provided the logarithm is undone with the corresponding base. The interactive uses log⁡10\log_{10} for directly readable axes; the lab uses ln⁡\ln.

Allocation laws and tokens per parameter

With vertices of accepted profiles, the optimal allocation fit is a log-log linear regression:

ln⁡N∗(Ci)=ln⁡k+aln⁡Ci,ln⁡D∗(Ci)=ln⁡h+bln⁡Ci.\ln N^\ast(C_i)=\ln k + a\ln C_i,\qquad \ln D^\ast(C_i)=\ln h + b\ln C_i .

Under exact C=6NDC=6ND, ln⁡D∗=ln⁡C−ln⁡6−ln⁡N∗\ln D^\ast=\ln C-\ln 6-\ln N^\ast, so b=1−ab=1-a and h=1/(6k)h=1/(6k) by construction: these are not two estimates, and presenting two intervals as independent duplicates evidence. The optimal token-to-parameter ratio is

r(C)=D∗N∗=C6N∗2=C1−2a6k2,r(C)=\frac{D^\ast}{N^\ast}=\frac{C}{6N^{\ast 2}}=\frac{C^{1-2a}}{6k^2},

constant only if a=1/2a=1/2. With a=0.513a=0.513, the ratio on Besiroglu’s surface falls from 24.6 at 6⋅10186\cdot10^{18} FLOPs to 21.0 at 3⋅10213\cdot10^{21}; one average hides this.

Chinchilla’s number 20 comes from this same arithmetic in table 3 of the paper (approach 1): a 1000 million parameter model with 20 200 million tokens, and a 67 000 million model with 1.5 trillion. It is a property of its corpus, architecture and accounting, not a mathematical constant. If you trained project p06’s 124M GPT, the Chinchilla rule would assign it about 2500 million tokens; knowing whether that is optimal for your corpus requires profiles on your corpus.

Fitting the line while treating vertices as exact data is the typical error here. Each vertex has the standard error from the preceding theorem, and all five are estimated using the same procedure. The correct way to propagate uncertainty is the next section’s bootstrap, which refits each parabola before fitting the line.

Bootstrap intervals that refit the profiles

Hoffmann obtains intervals by resampling 80 % of data 100 times and publishes the 10th and 90th percentiles: [0.462, 0.534][0.462,\,0.534] for aa and [0.483, 0.529][0.483,\,0.529] for bb in approach 2. They are not 95 % intervals, and their width (about seven hundredths) is the reference against which to compare a replication.

The nonparametric bootstrap requires choosing the resampling unit carefully. In the lab each configuration (budget, width) trains with three seeds, and each run has its own initialization and data stream derived from a configuration hash. Runs are independent by design, including across configurations. This permits resampling the three runs with replacement within each cell. If a seed shared data or weights between sizes, whole seed blocks would need resampling, and with only two or three seeds the bootstrap would have very few distinct resamples.

In each of 1000 replicates: resample runs within each cell, recalculate the 35 means, refit five parabolas using the acceptance rule and, only if all five vertices are valid, fit the line. Invalid replicates are counted and published; they are not replaced with the grid endpoint or central value. The same distribution yields intervals for N∗N^\ast, D∗=C/(6N∗)D^\ast=C/(6N^\ast) (with endpoints reversed because the relationship decreases) and rr, calculated replicate by replicate: dividing endpoints of DD and NN intervals would combine values that never occur together.

Two honest limitations. With three runs per cell, bootstrap variance of a mean is empirical variance with divisor 3, not 2: it underestimates the true one by factor 2/32/3, so bootstrap standard errors are about 18 % narrower. And percentile intervals describe only seed variation: they exclude parabola shape error, rate-rule error and changes of corpus or architecture. Increasing from 1000 to 10 000 replicates reduces percentile Monte Carlo noise but creates no new information.

Lab: five profiles on the RTX 4060

The project’s real experiment, with a GPT on text, occupies several GPU nights. To make the lab run in about seven GPU minutes with the same statistical structure, we replace language with an artificial source having both properties that create a size-data trade-off. There are 2142^{14} contexts with Zipf frequencies (pk∝k−1.3p_k\propto k^{-1.3}) and, for each context, a distribution over 32 symbols drawn from a Dirichlet(0.25). A small model cannot memorize rare-context distributions (capacity error); a large model with few tokens has not seen enough examples of them (data error). Minimum achievable loss is source entropy, 2.2497 nats.

The model is a perceptron with two hidden layers of width ww over the context’s 14 bits. All parameters participate in each example, so 6ND6ND is nearly exact accounting here rather than a rough proxy as in a transformer. Three seeds of a configuration train in parallel with batched products (baddbmm). Each training example is fresh, without repetition, and evaluation uses 100 000 fixed examples never seen in training.

[ ]Source, model and budgeted trainingLocal GPU
import math, json, hashlib, sqlite3, time
from pathlib import Path
import numpy as np
import torch
import torch.nn.functional as F
import matplotlib.pyplot as plt

dev = 'cuda' if torch.cuda.is_available() else 'cpu'
BITS, V, K = 14, 32, 2**14          # contexto de 14 bits, 32 símbolos de salida
g = torch.Generator().manual_seed(0)  # la fuente es fija: no depende de las semillas de los entrenamientos
zipf = torch.arange(1, K + 1, dtype=torch.float64) ** -1.3
zcum = (zipf.cumsum(0) / zipf.sum()).float()
perm = torch.randperm(K, generator=g)
gam = torch._standard_gamma(torch.full((K, V), 0.25), generator=g)
probs = gam / gam.sum(1, keepdim=True)          # Dirichlet(0.25) por contexto
H = -(probs * torch.log(probs.clamp_min(1e-30))).sum(1)
E_SOURCE = float((torch.diff(zcum, prepend=torch.zeros(1)) * H[perm]).sum())
zcum, perm, cum = zcum.to(dev), perm.to(dev), probs.cumsum(1).to(dev)
bitmask = 2 ** torch.arange(BITS, device=dev)

def sample(shape, gen):
    """Ejemplos frescos: contexto con frecuencia de Zipf y siguiente símbolo de su distribución."""
    u = torch.rand(shape, device=dev, generator=gen).reshape(-1)
    ctx = perm[torch.searchsorted(zcum, u).clamp_max(K - 1)]
    u2 = torch.rand(ctx.shape[0], 1, device=dev, generator=gen)
    y = torch.searchsorted(cum[ctx], u2).squeeze(1).clamp_max(V - 1)
    x = ((ctx[:, None] & bitmask) > 0).float() * 2 - 1
    return x.reshape(*shape, BITS), y.reshape(shape)

def n_params(w):
    # 14 -> w -> w -> 32 con sesgos: todos los parámetros participan en cada ejemplo
    return BITS * w + w + w * w + w + w * V + V

def width_for(n):
    return min(range(4, 600), key=lambda w: abs(math.log(n_params(w) / n)))

gen_eval = torch.Generator(device=dev).manual_seed(999)
X_EVAL, Y_EVAL = sample((1, 100_000), gen_eval)   # evaluación fija, nunca vista en entrenamiento

def forward(p, x):
    h = F.gelu(torch.baddbmm(p[1], x, p[0]))
    h = F.gelu(torch.baddbmm(p[3], h, p[2]))
    return torch.baddbmm(p[5], h, p[4])

def train_config(width, budget, seeds, lr, batch=2048):
    """Entrena len(seeds) réplicas independientes de una configuración en paralelo (bmm)."""
    S, n = len(seeds), n_params(width)
    tokens = int(budget // (6 * n))
    steps = tokens // batch
    if steps < 50:
        raise ValueError('menos de 50 actualizaciones')
    key = int(hashlib.sha256(f'{width}-{budget}-{seeds}'.encode()).hexdigest()[:8], 16)
    gi = torch.Generator(device=dev).manual_seed(key)
    gd = torch.Generator(device=dev).manual_seed(key + 1)
    def lin(i, o):
        bound = 1 / math.sqrt(i)
        return [((torch.rand(S, i, o, device=dev, generator=gi) * 2 - 1) * bound).requires_grad_(),
                ((torch.rand(S, 1, o, device=dev, generator=gi) * 2 - 1) * bound).requires_grad_()]
    p = lin(BITS, width) + lin(width, width) + lin(width, V)
    opt = torch.optim.Adam(p, lr=lr, fused=dev == 'cuda')
    warm = max(1, steps // 20)
    checkpoints = sorted({int(round(steps * f)) for f in np.geomspace(1 / 32, 1, 11)})
    curve = []
    def evaluate():
        with torch.no_grad():
            out = forward(p, X_EVAL.expand(S, -1, -1))
            return [float(F.cross_entropy(out[s], Y_EVAL[0])) for s in range(S)]
    t0 = time.time()
    for t in range(steps):
        # calentamiento del 5 % y coseno de 1 a 0.1 ajustado al horizonte de esta ejecución
        factor = min(1, (t + 1) / warm) * (0.1 + 0.45 * (1 + math.cos(math.pi * t / (steps - 1))))
        for group in opt.param_groups:
            group['lr'] = lr * factor
        x, y = sample((S, batch), gd)
        # media sobre S·batch por S: cada réplica recibe el gradiente de su propia pérdida media
        loss = F.cross_entropy(forward(p, x).reshape(-1, V), y.reshape(-1)) * S
        opt.zero_grad(set_to_none=True)
        loss.backward()
        opt.step()
        if t + 1 in checkpoints:
            curve.append([6 * n * (t + 1) * batch, evaluate()])
    final = curve[-1][1]
    if not all(math.isfinite(v) for v in final):
        raise ValueError('pérdida no finita')
    return dict(width=width, n=n, budget=budget, tokens=steps * batch, flops=6 * n * steps * batch,
                steps=steps, seeds=list(seeds), losses=final, curve=curve, secs=round(time.time() - t0, 1))

print('Dispositivo:', dev, '| entropía de la fuente (pérdida mínima alcanzable):', round(E_SOURCE, 4), 'nats')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Learning rate needs its own rule. In an initial attempt we used fixed rate 0.04, close to the best in a pilot at 101110^{11} FLOPs with batches of 4096, and the result is described after the analysis cell. A short sweep with rates 0.01, 0.02 and 0.04 and three widths per budget showed optimal rate depends on horizon. At 5⋅10105\cdot10^{10} FLOPs the best was 0.04, and at 4⋅10114\cdot10^{11} it was 0.02, at all three widths tested. The registered rule interpolates between them, η(C)=0.04 (C/5⋅1010)−1/3\eta(C)=0.04\,(C/5\cdot10^{10})^{-1/3}, common to all sizes of a profile. This is a minimal version of hyperparameter choice by scale: a poorly chosen rate for large models pushes the optimum toward smaller ones and biases aa downward.

The SQLite queue is from the infrastructure lesson: each configuration has a key hashing its complete configuration, completed results are retained and interruption repeats only incomplete work. Rerunning the cell retrains nothing; changing version, rate or batch does.

[ ]Five-profile queueLocal GPU
BUDGETS = [5e10, 1e11, 2e11, 4e11, 8e11]
OFFSETS = [-1.2, -0.8, -0.4, 0.0, 0.4, 0.8, 1.2]   # z = ln(N/N0), fijados en el registro previo
R_PILOT = 100                                       # tokens por parámetro del piloto a 1e11
SEEDS = (11, 22, 33)
def lr_rule(c):
    # registrada tras dos pilotos: 0.04 era la mejor a 5e10 y 0.02 a 4e11, en todas las anchuras probadas
    return round(0.04 * (c / 5e10) ** (-1 / 3), 5)
plan = {}
for c in BUDGETS:
    n0 = math.sqrt(c / (6 * R_PILOT))
    plan[c] = sorted({width_for(n0 * math.exp(z)) for z in OFFSETS})
    assert len(plan[c]) == len(OFFSETS)

root = Path('resultados/p14-l05')
root.mkdir(parents=True, exist_ok=True)
db = sqlite3.connect(root / 'isoflop.sqlite3')
db.execute('CREATE TABLE IF NOT EXISTS runs (id TEXT PRIMARY KEY, cfg TEXT, state TEXT, result TEXT, error TEXT)')
VERSION = 'isoflop-zipf-v2'
jobs = [dict(version=VERSION, width=w, budget=c, seeds=list(SEEDS), lr=lr_rule(c), batch=2048, device=dev)
        for c in BUDGETS for w in plan[c]]
def job_key(job):
    return hashlib.sha256(json.dumps(job, sort_keys=True).encode('utf-8')).hexdigest()
with db:
    db.execute("UPDATE runs SET state='pending' WHERE state='running'")   # un único trabajador
    for job in jobs:
        db.execute("INSERT OR IGNORE INTO runs VALUES (?,?,'pending',NULL,NULL)",
                   (job_key(job), json.dumps(job, sort_keys=True)))
t0 = time.time()
for job in jobs:
    key = job_key(job)
    with db:
        claimed = db.execute("UPDATE runs SET state='running' WHERE id=? AND state='pending'", (key,)).rowcount
    if not claimed:
        continue
    try:
        value = train_config(job['width'], job['budget'], job['seeds'], job['lr'], job['batch'])
        with db:
            db.execute("UPDATE runs SET state='done', result=? WHERE id=?", (json.dumps(value), key))
    except Exception as exc:
        with db:
            db.execute("UPDATE runs SET state='failed', error=? WHERE id=?", (repr(exc), key))
records = []
for job in jobs:
    state, result, error = db.execute('SELECT state, result, error FROM runs WHERE id=?', (job_key(job),)).fetchone()
    if state != 'done':
        raise RuntimeError(f'configuración {job} en estado {state}: {error}')
    records.append(json.loads(result))
db.close()
print('Configuraciones:', len(records), 'x', len(SEEDS), 'semillas =', len(records) * len(SEEDS), 'entrenamientos')
print('Tiempo de GPU acumulado:', round(sum(r['secs'] for r in records)), 's; esta llamada:', round(time.time() - t0), 's')
for c in BUDGETS:
    rows = [r for r in records if r['budget'] == c]
    print(f'C={c:.0e}  tasa {lr_rule(c)}  anchuras {plan[c]}  N de {rows[0]["n"]} a {rows[-1]["n"]}  pasos de {rows[-1]["steps"]} a {rows[0]["steps"]}')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Parabolas, bootstrap, allocation law and envelopeLocal GPU
def profile_fit(n, losses):
    """Parábola en x = ln N; None si no hay un mínimo interior identificable."""
    n, losses = np.asarray(n, float), np.asarray(losses, float)
    if len(np.unique(n)) < 3 or np.any(n <= 0) or not np.all(np.isfinite(losses)):
        return None
    x = np.log(n); center = x.mean(); z = x - center
    coeff, _, rank, _ = np.linalg.lstsq(np.column_stack([z * z, z, np.ones_like(z)]), losses, rcond=None)
    c2, c1, c0 = coeff
    if rank < 3 or c2 <= 0:
        return None
    xs = center - c1 / (2 * c2)
    if not x.min() < xs < x.max():
        return None
    return dict(n=float(np.exp(xs)), c2=float(c2), c1=float(c1), c0=float(c0), center=float(center),
                resid=losses - (c2 * z * z + c1 * z + c0))

def profile_table(c, draw=None):
    rows = sorted((r for r in records if r['budget'] == c), key=lambda r: r['n'])
    L = np.array([r['losses'] for r in rows])          # (tamaños, semillas)
    if draw is not None:
        L = np.take_along_axis(L, draw, axis=1)
    return np.array([r['n'] for r in rows], float), L.mean(1), L

def law(cs, ns):
    slope, intercept = np.polyfit(np.log(cs), np.log(ns), 1)
    return float(slope), float(intercept)

S = len(SEEDS)
fits = [profile_fit(*profile_table(c)[:2]) for c in BUDGETS]
assert all(f is not None for f in fits), 'algún perfil no tiene mínimo interior'
rng = np.random.default_rng(2026)
REPS = 1000
boot_n = [[] for _ in BUDGETS]; boot_a = []; boot_r = [[] for _ in BUDGETS]
bad = [0] * len(BUDGETS); bad_joint = 0
for _ in range(REPS):
    found = []
    for i, c in enumerate(BUDGETS):
        draw = rng.integers(0, S, size=(len(plan[c]), S))   # ejecuciones con reposición dentro de cada celda
        f = profile_fit(*profile_table(c, draw)[:2])
        if f is None:
            bad[i] += 1
        else:
            boot_n[i].append(f['n']); boot_r[i].append(c / (6 * f['n'] ** 2))
        found.append(f)
    if any(f is None for f in found):
        bad_joint += 1
    else:
        boot_a.append(law(BUDGETS, [f['n'] for f in found])[0])

print('   C        N*   N* p5-p95          D*   D*/N*  D*/N* p5-p95  inválidas  x*-ln N0  EE(ln N*) teoría/boot  RMS resid/EE')
for i, (c, f) in enumerate(zip(BUDGETS, fits)):
    ns, means, L = profile_table(c)
    z = np.log(ns) - f['center']
    sigma = float(np.sqrt(np.mean(L.var(axis=1, ddof=1) / S)))       # error típico de una media
    se_theory = sigma / (2 * f['c2'] * np.sqrt(np.sum(z ** 2)))       # teorema: kappa = 2 c2
    se_boot = float(np.std(np.log(boot_n[i])))
    lo, hi = np.percentile(boot_n[i], [5, 95]); rlo, rhi = np.percentile(boot_r[i], [5, 95])
    rms = float(np.sqrt(np.mean(f['resid'] ** 2)))
    shift = math.log(f['n']) - 0.5 * math.log(c / (6 * R_PILOT))
    print(f'{c:.0e}  {f["n"]:7.0f}  [{lo:6.0f}, {hi:6.0f}]  {c / (6 * f["n"]):9.3g}  {c / (6 * f["n"] ** 2):6.1f}'
          f'  [{rlo:5.1f}, {rhi:5.1f}]  {bad[i]:4d}/{REPS}  {shift:+8.3f}  {se_theory:10.4f} / {se_boot:.4f}  {rms / sigma:8.1f}')
a_hat, logk = law(BUDGETS, [f['n'] for f in fits])
assert len(boot_a) >= 0.8 * REPS
pa = np.percentile(boot_a, [5, 10, 90, 95])
print(f'\nEnfoque 2: a = {a_hat:.3f}  (p5-p95 [{pa[0]:.3f}, {pa[3]:.3f}], p10-p90 [{pa[1]:.3f}, {pa[2]:.3f}])')
print(f'           b = 1 - a = {1 - a_hat:.3f}  (p5-p95 [{1 - pa[3]:.3f}, {1 - pa[0]:.3f}]);  D*/N* crece como C^{1 - 2 * a_hat:.3f}')
print('Réplicas conjuntas inválidas:', bad_joint, '/', REPS)

# Enfoque 1 con las mismas ejecuciones: a cada presupuesto, la curva con menor pérdida interpolada en ese cómputo
def envelope(c):
    best = None
    for r in records:
        fl = np.log([p[0] for p in r['curve']]); loss = np.array([np.mean(p[1]) for p in r['curve']])
        fl[-1] = max(fl[-1], math.log(r['budget']))   # el redondeo a lotes deja un resto de presupuesto
        if fl[0] <= math.log(c) <= fl[-1]:
            value = float(np.interp(math.log(c), fl, loss))
            if best is None or value < best[0]:
                best = (value, r['n'], r['budget'])
    return best
env = [envelope(c) for c in BUDGETS]
a_env = law(BUDGETS, [e[1] for e in env])[0]
print('\nEnfoque 1 (envolvente): N ganador', [e[1] for e in env], '| presupuesto de la ejecución ganadora',
      [f'{e[2]:.0e}' for e in env], f'| a = {a_env:.3f}')

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4))
for i, (c, f) in enumerate(zip(BUDGETS, fits)):
    ns, means, L = profile_table(c)
    col = plt.cm.viridis(i / (len(BUDGETS) - 1))
    ax1.errorbar(ns, means, yerr=L.std(axis=1, ddof=1), fmt='o', ms=4, color=col, label=f'C = {c:.0e}')
    xx = np.linspace(np.log(ns.min()), np.log(ns.max()), 100); z = xx - f['center']
    ax1.plot(np.exp(xx), f['c2'] * z * z + f['c1'] * z + f['c0'], color=col)
    ax1.plot(f['n'], f['c0'] - f['c1'] ** 2 / (4 * f['c2']), 'k*', ms=9)
ax1.set(xscale='log', xlabel='Parámetros N', ylabel='Pérdida de evaluación (nats)', title='Perfiles isoFLOP')
ax1.legend(fontsize=8)
cs = np.geomspace(BUDGETS[0], BUDGETS[-1], 50)
ax2.errorbar(BUDGETS, [f['n'] for f in fits],
             yerr=[[f['n'] - np.percentile(b, 5) for f, b in zip(fits, boot_n)],
                   [np.percentile(b, 95) - f['n'] for f, b in zip(fits, boot_n)]], fmt='o', label='Vértices (p5-p95)')
ax2.plot(cs, np.exp(logk) * cs ** a_hat, label=f'Enfoque 2: a = {a_hat:.3f}')
ax2.plot(cs, np.sqrt(cs / (6 * R_PILOT)), ':', label='Centro de la rejilla (a = 1/2)')
ax2.plot(BUDGETS, [e[1] for e in env], 's', mfc='none', label=f'Envolvente: a = {a_env:.3f}')
ax2.set(xscale='log', yscale='log', xlabel='Presupuesto C (FLOPs)', ylabel='N óptimo', title='Ley de asignación')
ax2.legend(fontsize=8)
fig.tight_layout()
plt.show()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

This is the lesson’s verifiable result. All five parabolas have an interior minimum and none of the 1000 replicates is invalid. Vertices go from 9439 parameters at 5⋅10105\cdot10^{10} FLOPs to 28 278 at 8⋅10118\cdot10^{11}, with 5–95 intervals of 2 % or 3 % on each side. Root mean squared residual ranges from 0.4 to 1.1 times the means’ standard error: the parabola explains points to seed-noise level and no asymmetry is visible at this resolution. Standard errors of ln⁡N∗\ln N^\ast predicted by the theorem (0.012 to 0.019) are of the same order as bootstrap ones and somewhat larger, as expected from factor 2/32/3 and estimating σ\sigma with only three seeds.

The fitted law is a=0.397a=0.397, with 5th and 95th percentiles [0.387, 0.408][0.387,\,0.408] and 10th and 90th percentiles [0.389, 0.406][0.389,\,0.406], hence b=0.603b=0.603. The ratio D∗/N∗D^\ast/N^\ast rises from 93.5 to 166.7 across the range, as C0.206C^{0.206}: in this source data must grow faster than parameters. Also note column x*-ln N0: the grid was centered assuming a=1/2a=1/2, and since the real exponent is smaller, the optimum shifts left of grid center, from +0.033+0.033 to −0.256-0.256. The prediction is (0.5−0.397)ln⁡16≈0.29(0.5-0.397)\ln16\approx0.29, exactly as observed. Here the shift fits comfortably within the grid, which reaches ±1.2\pm1.2, but with a budget range ten times larger it would not: the next batch of profiles should be centered with the measured law, not the registered one.

The initial run with fixed rate 0.04 shows the opposite. Two runs diverged there, widths 134 and 169 at 8⋅10118\cdot10^{11} FLOPs. That profile had its three smallest sizes tied at median 2.403 nats and a mean dominated by the diverged run. With the rate rule, minimum loss of that same profile falls to 2.383. Neither defect, an optimum pushed toward small sizes and a profile dominated by an anomalous run, would be detected by any bootstrap interval: they are detected by inspecting points, seeds and residuals.

Comparison with the first approach and the paper

The cell’s last part applies the first approach to the same runs: for each budget it seeks, among all training curves reaching it, the lowest loss interpolated at that compute. The five winners are runs designed for that same budget and evaluated at the end: no intermediate point of a longer run wins, because its rate has not yet fallen. This reproduces Hoffmann’s cosine-schedule observation. The envelope can choose only grid sizes (9060, 12 912, 18 225, 25 700 and 24 420 parameters; the last is smaller than the previous through discretization alone) and gives a=0.385a=0.385. It is slightly below the approach 2 interval, and the difference comes from discretization: the profile interpolates between sizes, the envelope does not.

Both estimates use the same runs, so agreement is a consistency check, not an independent replication. When they disagree, the difference is localized budget by budget: the envelope offers only discrete grid sizes, while the profile interpolates between them.

Against the paper, separate method from constants. Our a=0.397a=0.397 [0.387, 0.408][0.387,\,0.408] is clearly below Hoffmann’s 0.490.49 [0.462, 0.534][0.462,\,0.534], and the ratio, 94 to 167, is very different from 20. There is no contradiction: both depend on source, architecture and how NN and DD are counted, and a Zipf source with a perceptron is not a text corpus with a transformer. In the parametric surface, a=β/(α+β)<1/2a=\beta/(\alpha+\beta)<1/2 is equivalent to β<α\beta<\alpha: loss falls more slowly with data than with parameters. This is plausible in a task memorizing rare-context distributions that must be seen many times, but we have not tested it. The procedure does transfer. In the real project, with a GPT and text corpus, an exponent near 1/2 is expected; a result like ours would need explanation before publication.

The reanalysis by Besiroglu and colleagues is the other reference. They reconstructed about 240 points from figure 4, refitted the third approach and found its published estimates incompatible with approaches 1 and 2: they implied about 70 tokens per parameter versus Chinchilla’s 20, and intervals so narrow they would have required over 600 000 experiments, when fewer than 500 were likely performed. Their refit gives a=0.513a=0.513 and about 20 tokens per parameter, consistent with approaches 1 and 2. Thus the isoFLOP profile approach is one of two of the paper’s three approaches that withstand review. Do not cite this as though they retrained models: they worked on data extracted from figures.

Exercises

NumericFrom log size to parameters
Loss is fitted as L(x)=0.05x2−0.8x+6.4L(x)=0.05x^2-0.8x+6.4, where x=ln⁡Nx=\ln N is the natural logarithm of parameter count. What size NN minimizes the parabola?
NumericHow much the vertex moves
A profile has curvature κ=ℓ′′(x∗)=0.10\kappa=\ell''(x^\ast)=0.10 in x=ln⁡Nx=\ln N and is measured with the seven-point grid z∈{−1.2,−0.8,−0.4,0,0.4,0.8,1.2}z\in\{-1.2,-0.8,-0.4,0,0.4,0.8,1.2\} centered at the optimum. Each point is a mean with standard error σ=0.002\sigma=0.002 nats. According to the lesson's theorem, what is the standard error of x^∗=ln⁡N^∗\hat x^\ast=\ln \hat N^\ast?
NumericA ratio that is not constant
In the lab, N∗=kCaN^\ast=kC^{a} with a≈0.40a\approx0.40 and, at C=1011C=10^{11} FLOPs, the optimal ratio is D∗/N∗≈100D^\ast/N^\ast\approx100. Under C=6NDC=6ND and assuming the law holds, what ratio is predicted at C=1013C=10^{13} FLOPs? Use exact a=0.40a=0.40 and 100100.
QuizCenter the grid
You plan profiles using a prior optimum prediction. Why center each profile's sizes on it, symmetrically in ln N?
QuizA ratio very different from 20
Your replication obtains five profiles with interior minima, residuals at noise level, a = 0.40 with interval [0.39, 0.41], and a D/N ratio rising from 94 to 167. What conclusion is most defensible?
CodeMinimum and resampling interval
Implement isoflop_minimum(sizes, losses, n_boot). sizes contains at least three distinct positive sizes. losses is a finite matrix of shape (sizes, replicates), with at least two replicates per size. n_boot is a positive integer. Assume all replicates independent, as in the lab. Fit by least squares a parabola to each row's mean against ln(size), centering the abscissa. Raise ValueError if the inputs fail these conditions, rank is insufficient, curvature is not positive or the vertex lies outside the range. Then resample replicates with replacement within each size using numpy.random.default_rng(12345), refitting each replicate and discarding invalid fits. If fewer than 80 % are valid or the distribution is degenerate, raise ValueError. Return the optimal size and 5–95 percentile interval of valid sizes.
import numpy as np

def isoflop_minimum(sizes, losses, n_boot):
  pass
Shift+Enter to run
Key idea

An isoFLOP profile fixes compute and compares final losses of runs designed for that budget; in ln⁡N\ln N its valley is almost a parabola whose vertex has shape bias −(τ/κ)m4/(6m2)-(\tau/\kappa)m_4/(6m_2) and standard error σ/(κnm2)\sigma/(\kappa\sqrt{nm_2}) on a centered grid. Vertices give N∗∝CaN^\ast\propto C^a and, under 6ND6ND, b=1−ab=1-a and ratio D∗/N∗∝C1−2aD^\ast/N^\ast\propto C^{1-2a}. Intervals come from a bootstrap refitting every parabola. What transfers from Chinchilla to another problem is the procedure, not 20, or even the exponent if the data source changes in nature.