First approach: the envelope of training curves
Construct and evaluate a loss envelope from finite training curves.
After this lesson you can
- Run training series with several durations per size.
- Interpolate curves and build the minimum-loss envelope by compute.
- Fit power laws for optimal size and tokens with uncertainty.
- Compare exponents with published and preregistered predictions.
Before you start
A frontier nobody trained as a model
You have a collection of loss curves: each corresponds to a model size and a training duration. For a given budget, draw a vertical line and see which available curve lies lowest. As the line moves, the winning curve can change. The path traced by the minimum is called the lower envelope: it is not the history of a single training run, but a selection among many.
The figure shows exactly that with the 243 runs you will train in this lesson’s lab: eleven widths of a tiny transformer, up to eight durations per width, each with its own schedule, and three seeds per pair, averaged. The horizontal axis is on a logarithmic scale, so equal distances represent the same compute factor; each curve starts at its first evaluation and ends at the last step of its schedule, marked by a dot. Below, winning size at each budget on a log-log scale: its slope is exponent sought by the first approach.
Three details deserve attention. The envelope has corners where the winning curve changes, even if each curve is smooth, and winning size is a step function of : the line below is fitted to steps, and the size grid limits resolution. A minimum among available models does not show that size is optimal among all possible ones: removing a size keeps the envelope the same or raises it, never lowers it. And a winner at the edge of the grid (gray points) warns that candidates may be missing on its side; therefore the fit uses only budgets whose winner has smaller and larger candidates.
In the project curves come from finite training runs, not a continuous formula. Their support starts at the first measurement and ends at the last; we must not invent losses outside it. Different durations also use different rate schedules. The schedule lesson showed why intermediate loss from a long run can differ from final loss of a short one with the same tokens. This lesson preserves, measures and documents that difference.
What Hoffmann and colleagues did
The first approach of Hoffmann and colleagues, section 3.1, trains a family from approximately 70 million to over 10 billion parameters. For each size they launch four durations with horizons spanning a factor of 16 and a cosine schedule reducing rate by a factor of 10. The authors smooth and interpolate full curves and, at 1500 logarithmically spaced budgets, select the run with lowest loss. They then fit and .
A crucial nuance: they did not restrict the candidate set to endpoints. The text says selected points turned out to lie within the last 15 % of their respective runs. That is an observation from the experiment, not a rule we can impose and attribute to them retroactively. Appendix D.1 reports Gaussian smoothing with a 10-step window and maximum rates of for the smallest models and for the largest. It also describes that, in their analysis, a schedule exceeding step count by more than 25 % perceptibly hurts performance. These numbers depend on their models and data and do not determine our rate.
Table 2 publishes for this approach with 10th and 90th percentiles of 0.488 and 0.502, and with percentiles 0.501 and 0.512. Their description uses 100 resamples of 80 % of the data. These endpoints are the 10th and 90th percentiles, not a 95 % interval, and are not an independent measure of all uncertainty sources. Their precision does not automatically transfer to a much smaller GPU, corpus and grid.
In the same table the isoFLOP profile approach obtains and , while the parametric fit gives 0.46 and 0.54. These are distinct estimators sharing decisions and data; approximate agreement does not constitute three independent replications. The reanalysis by Besiroglu and colleagues particularly questions the published parametric fit and intervals using data reconstructed from a figure: their reestimate gives and , that is , compatible with approaches 1 and 2, and they estimate that intervals as narrow as those published would require over 600 000 experiments. Do not automatically attribute that criticism to envelope calculation: first identify which method and data are being evaluated.
From a collection of curves to a function
Let and be run ‘s interpolated curve inside that interval. For budget , define candidate set . If it is nonempty, the observed envelope and a winner are
The definition allows ties. For a reproducible program fix a deterministic rule: in this lab, for identical losses, choose the smaller size and then the shorter horizon. If there are no candidates, the result is missing, not zero or the last observed value. If only one size is available the envelope exists mathematically but does not compare sizes; the lab requires at least two distinct sizes before recording a point for the fit.
Runs of the same size and horizon can have several seeds. Selecting the lowest individual loss among all of them would reward the lucky seed. In the lab we average curves of the three seeds of the same design (same width and horizon) before comparing configurations. This criterion is an analysis choice: in research you could select on tuning seeds and evaluate on held-out seeds. Do not average runs of different duration as though they shared a schedule; their optimization histories differ.
The calculation is an approximation used as an axis. Counted parameters, processed tokens, attention and vocabulary can alter its difference from actual FLOPs. The FLOP convention must be identical across all points and retained with the result. If using full batches, reached budgets are discrete. Recording nominal cost without actual cost can place a loss at the wrong position on the axis.
A lab is a family of runs
For each size fix several separate horizons, each with its own schedule decaying from start to finish. There are two reasonable ways to choose them. Hoffmann fixes each size’s horizons in tokens; alternatively fix a few common final budgets and give each size tokens. The second guarantees that every size competes throughout , so an interior winner always has rivals on both sides; its cost is that small models train many steps at high budgets. With multiple seeds, each size, horizon and seed combination is a full run, with newly initialized weights and states. One long run cut at several times does not reproduce that design: it would have one schedule and each cut would share trajectory and noise. Horizon density matters more than it seems: between two consecutive endpoints of one size, the envelope can only use intermediate segments of the longer run, whose rate has not yet annealed. Widely spaced horizons pass that sawtooth to the envelope. Keep corpus, split, tokenizer, precision, evaluation and optimizer the same except for recorded modifications.
The learning-rate sweep by scale must already have been performed or budgeted separately. A winning curve may win because its size was better tuned, not because it is intrinsically optimal. Record peak rate, warmup, final factor, effective batch, context length, actual steps and seeds. Each curve needs enough points for interpolation: two permit a line, but a line over a long region does not necessarily describe training.
To compare durations, define which loss you record. The paper analyzes smoothed training loss, which in its regime (each token seen once) is nearly out-of-sample loss. The lab measures cross-entropy on 512 held-out chains from the same Markov source, never used for training, at about 24 logarithmically spaced evaluations per run. Since the source is known, so is the irreducible floor: chain entropy, about 1.63 nats per token. Comparison with the paper is methodological: the absolute values of the losses are not comparable.
A resumable queue must preserve each seed’s result before marking it finished. If a process dies, identify its attempt and restart it or recover from a checkpoint with weights, optimizer, schedule, randomness and data position. The sweep infrastructure describes that distinction. Our example uses a single-worker queue and restarts interrupted work from scratch: it does not claim exact internal-state resumption.
Interpolate without inventing data
In an observed interval between and , with and , we can interpolate loss linearly in log budget:
This is one choice, not the only one. It keeps the interpolated value between the endpoints and puts the midpoint at geometric mean . Loss is interpolated linearly, not its logarithm. If you have reason to interpolate , require positive losses and document the implicit model. The lab averages seeds before interpolation and does not extrapolate at either end.
High-degree polynomial interpolation can oscillate between observations, especially with unevenly spaced points. A cubic spline facilitates continuous derivatives but does not guarantee a loss curve stays monotone or within neighboring values. Compare the chosen method with linear interpolation and check crossings that determine changes of winner. A smooth curve is not new evidence: the spline only organizes available data.
Smoothing also changes the estimator, not always for the better. Hoffmann smooths with a 10-step window over curves tens of thousands of steps long: the filter affects a tiny fraction of each run. If you apply a Gaussian filter with one-point standard deviation to 24 logarithmically spaced evaluations, each point mixes with neighbors roughly a factor 1.2 of compute away, and the last point, which matters because it closes the schedule, is averaged with earlier, higher losses: it biases endpoints upward precisely where runs finish and favors intermediate segments of long curves. The lab measures loss on a fixed held-out set and averages three seeds, so we do not smooth; if your metric is noisy, smooth on the step scale, not the evaluation scale, and repeat the analysis without smoothing.
If compute points are duplicated within a run, first decide how to aggregate them; the interpolator needs strictly increasing coordinates. Two observations at the same cost may correspond to repeated validation, not two distinct steps. If a value is missing or loss is nonfinite, stop or mark the segment invalid under a recorded rule. An interpolator crossing a long observation gap can give misleading visual precision even when its endpoints are valid.
The envelope can be biased downward when selecting the minimum of many noisy curves. The more candidates compared, the more opportunities to choose one with a favorable fluctuation. Smoothing reduces some noise but does not eliminate selection. Seed count, correlation between points of one run and evaluation strategy must enter uncertainty analysis. Repeating hundreds of interpolated queries on the same curve does not create hundreds of independent experiments.
Fit a law and its uncertainty
If a power law is appropriate over the measured interval, with becomes a line:
The slope of an intercept regression on and estimates . For two distinct points it is ; with more points a line is fitted to all. Choosing a uniform grid in changes relative region weights compared with one uniform in : document that decision. Power-law regression also requires inspecting residuals and range sensitivity.
Under the exact relation used in analysis, . For the same budgets, a log regression with intercept satisfies : . These are not two independent measurements under this proxy. If FLOPs are computed with a formula including other terms, or different points and weights are used, the identity may not hold.
Irreducible loss mainly affects fitting a loss law, for example . Fitting a line to without accounting for can curve the relationship or bias . The envelope and allocation laws and do not require subtracting to calculate slopes; do not confuse these regressions. If is estimated from the same points, propagate its uncertainty and range choice.
Why use log scale rather than least-squares fitting on a linear scale? Because allocation-law error is multiplicative: being wrong by factor 1.5 in size is equally serious with or parameters. On a linear scale, residuals at the largest budgets are orders of magnitude larger and the fit is decided by the last two or three points; a line on a linear scale is a different model with no exponent. The logarithm converts relative errors into additive errors of similar variance, which ordinary regression assumes.
For an interval for , the regression’s confidence interval does not work: envelope points are not independent observations but readings of a few curves. The lab resamples entire seeds and reconstructs the envelope in each replicate; the resampling section explains what variation this captures and what it does not. Nor should you publish a slope interval if the winner is always an edge size and the true frontier lies outside the grid. In that case retain the chart and declare allocation unidentified in that range. Extending the grid after seeing the result is exploratory investigation and must be recorded as such.
Lab: a family of GPU runs
The lab replicates the complete first approach at toy scale: it trains, constructs the envelope, fits and with an interval and compares them with the paper and with the preregistration from the project’s first lesson, which predicted between 0.4 and 0.6. Data are from the infrastructure lesson: sequences of a fixed Markov chain over 64 symbols, whose transition matrix has Gaussian logits of scale 3. The task has the structure needed for an allocation law. A model of width can represent logits of rank at most on the transition matrix, so capacity limits loss; and each token is a new sample, so more data also reduce it. There is a trade-off at fixed compute, and the irreducible floor is known.
The model is a one-block, two-head transformer with fourfold MLP and context 16, with all parameters counted in (with , embeddings carry much weight, so convention matters). What is new is training: instead of launching 243 processes, the cell stacks parameters of all runs of one width in a matrix, one row per run, and trains them together in one graph. Each row has its own schedule: 10-step warmup and cosine from peak rate to one tenth at the end of its horizon; when that horizon ends, its rate becomes zero and the row stops changing. AdamW is elementwise, so rows are exactly independent runs with their own initialization and moments. Rows with the same seed start from the same weights and see the same batches: they differ only in horizon, making duration comparison a paired experiment.
Batches are sampled with replacement from a pool of 4.2 million tokens, and the longest run processes 2.7 million, so windows partly overlap but there are no repeated epochs. Loss is evaluated on 512 held-out chains at 24 logarithmically spaced points per run, and each point costs per step under the proxy, using steps actually taken.
import math
import json
import time
import hashlib
import sqlite3
import tempfile
from pathlib import Path
import numpy as np
import torch
import torch.nn.functional as F
import matplotlib.pyplot as plt
device = 'cuda' if torch.cuda.is_available() else 'cpu'
V, T, B = 64, 16, 32 # vocabulario, contexto, secuencias por paso
# Datos: cadena de Markov fija sobre 64 tokens, como en la lección de infraestructura.
P = (3.0 * torch.randn(V, V, generator=torch.Generator().manual_seed(0))).softmax(-1)
def chains(n, length, seed):
gen = torch.Generator().manual_seed(seed)
x = torch.empty(n, length, dtype=torch.long)
x[:, 0] = torch.randint(V, (n,), generator=gen)
for i in range(1, length):
x[:, i] = torch.multinomial(P[x[:, i - 1]], 1, generator=gen).squeeze(1)
return x
pool = chains(8192, 512, seed=1).to(device) # 4.2 millones de tokens de entrenamiento
held = chains(512, T + 1, seed=2).to(device) # evaluación: cadenas nuevas
floor = -torch.log(P[held[:, :-1].cpu(), held[:, 1:].cpu()]).mean().item()
def n_params(d):
# embeddings V·d y T·d, bloque 12d² (atención 4d², MLP 8d²), tres LayerNorm 6d, salida d·V
return V * d + T * d + 12 * d * d + 6 * d + d * V
def shapes(d):
return dict(tok=(V, d), pos=(T, d), qkv=(d, 3 * d), proj=(d, d), up=(d, 4 * d),
down=(4 * d, d), out=(d, V), n1w=(d,), n1b=(d,), n2w=(d,), n2b=(d,), nfw=(d,), nfb=(d,))
def init_params(d, seeds):
"""Una fila por modelo: los parámetros de cada ejecución, aplanados en un solo vector."""
rows = []
for s in seeds:
g = torch.Generator().manual_seed(s)
parts = []
for name, shape in shapes(d).items():
if name in ('tok', 'pos'):
w = torch.randn(shape, generator=g) # como nn.Embedding
elif name.endswith('w'):
w = torch.ones(shape) # LayerNorm
elif name.endswith('b'):
w = torch.zeros(shape)
else: # como nn.Linear
w = (torch.rand(shape, generator=g) * 2 - 1) / math.sqrt(shape[0])
parts.append(w.flatten())
rows.append(torch.cat(parts))
return torch.stack(rows).to(device).requires_grad_()
def unpack(W, d):
p, i = {}, 0
for name, shape in shapes(d).items():
size = math.prod(shape)
p[name] = W[:, i:i + size].reshape(W.shape[0], *shape)
i += size
return p
def norm(x, w, b):
x = (x - x.mean(-1, keepdim=True)) / torch.sqrt(x.var(-1, unbiased=False, keepdim=True) + 1e-5)
return x * w[:, None, None] + b[:, None, None]
def forward(p, ids):
"""ids: (M, lote, T). Devuelve logits (M, lote, T, V). Un bloque, dos cabezas."""
M, b, t = ids.shape
d = p['tok'].shape[-1]
x = p['tok'][torch.arange(M, device=ids.device)[:, None, None], ids] + p['pos'][:, None, :t]
q, k, v = torch.einsum('mbtd,mde->mbte', norm(x, p['n1w'], p['n1b']), p['qkv']).chunk(3, -1)
split = lambda z: z.reshape(M * b, t, 2, d // 2).transpose(1, 2)
a = F.scaled_dot_product_attention(split(q), split(k), split(v), is_causal=True)
x = x + torch.einsum('mbtd,mde->mbte', a.transpose(1, 2).reshape(M, b, t, d), p['proj'])
h = F.gelu(torch.einsum('mbtd,mde->mbte', norm(x, p['n2w'], p['n2b']), p['up']))
x = x + torch.einsum('mbtd,mde->mbte', h, p['down'])
return torch.einsum('mbtd,mdv->mbtv', norm(x, p['nfw'], p['nfb']), p['out'])
def member_loss(p, x):
logits = forward(p, x[..., :-1])
return F.cross_entropy(logits.reshape(-1, V), x[..., 1:].reshape(-1),
reduction='none').reshape(x.shape[0], -1).mean(1)
def schedule(H, warmup=10):
"""Factor de la tasa en cada paso de una ejecución de H pasos: calentamiento lineal y coseno de 1 a 0.1."""
t = np.arange(H)
return np.minimum(1.0, (t + 1) / warmup) * (0.1 + 0.45 * (1 + np.cos(np.pi * t / (H - 1))))
def eval_steps(H, n_evals=24):
return np.unique(np.geomspace(max(2, H // 50), H, n_evals).round().astype(int)).tolist()
def train_family(d, steps, seeds, lrs):
"""Entrena a la vez una ejecución completa por cada combinación de horizonte, semilla y tasa,
todas de anchura d. Cada una tiene su propio coseno; las de la misma semilla parten de los mismos
pesos y ven los mismos lotes. Al terminar su horizonte, la tasa de una ejecución pasa a cero."""
members = [(H, s, lr) for lr in lrs for s in seeds for H in steps]
M, total = len(members), max(steps)
W = init_params(d, [s for _, s, _ in members])
rates = np.zeros((total, M), dtype=np.float32)
for i, (H, _, lr) in enumerate(members):
rates[:H, i] = lr * schedule(H)
rates = torch.tensor(rates, device=device)
m1, m2 = torch.zeros_like(W), torch.zeros_like(W)
gens = {s: torch.Generator(device=device).manual_seed(10_000 + s) for s in seeds}
marks = {H: set(eval_steps(H)) for H in steps}
curves = [[] for _ in members]
window = torch.arange(T + 1, device=device)
for t in range(total):
batch = {}
for s in seeds:
rows = torch.randint(pool.shape[0], (B,), generator=gens[s], device=device)
cols = torch.randint(pool.shape[1] - T, (B,), generator=gens[s], device=device)
batch[s] = pool[rows[:, None], cols[:, None] + window]
x = torch.stack([batch[s] for _, s, _ in members])
(g,) = torch.autograd.grad(member_loss(unpack(W, d), x).sum(), W)
with torch.no_grad(): # AdamW sin decaimiento, elemento a elemento: filas independientes
m1.mul_(0.9).add_(g, alpha=0.1)
m2.mul_(0.999).addcmul_(g, g, value=0.001)
denom = (m2 / (1 - 0.999 ** (t + 1))).sqrt_().add_(1e-8)
W.sub_(rates[t][:, None] * (m1 / (1 - 0.9 ** (t + 1))) / denom)
if any(t + 1 in marks[H] for H in steps):
with torch.no_grad():
ev = member_loss(unpack(W, d), held.expand(M, *held.shape)).tolist()
for i, (H, _, _) in enumerate(members):
if t + 1 in marks[H]:
curves[i].append((t + 1, ev[i]))
n, out = n_params(d), []
for i, (H, s, lr) in enumerate(members):
done, losses = zip(*curves[i])
out.append(dict(width=d, n=n, steps=H, seed=s, lr=lr, tokens=[B * T * k for k in done],
flops=[6 * n * B * T * k for k in done], losses=list(losses)))
return outnpm run lab and open the connection link.The sum of row losses has, with respect to each row, exactly the gradient of its own loss, because no row participates in another’s loss. Therefore one autograd.grad per step suffices. Cost per step is nearly that of one model, since on a GPU these tiny models are limited by operation-launch latency rather than arithmetic: adding horizons or seeds to a family costs very little, and the longest horizon dominates.
The next cell defines the design and executes it in a resumable SQLite queue. Eleven widths, from 8 to 48 (1968 to 34 848 parameters). Eight common final budgets from to FLOPs, geometrically spaced: each width receives the nearest integer step count for each, minimum 50 (horizons repeated due to that minimum are merged). Three seeds. Before each family, a pilot with seed 0, excluded from analysis, chooses peak rate from at the FLOP horizon, a reduced version of the learning-rate sweep by scale. Each job is a complete family keyed by its canonical configuration: if the cell is interrupted, relaunching reuses completed families and restarts the interrupted one from scratch, without pretending to resume internal state. On a laptop GPU shared with other processes the first run takes about 12 minutes (considerably longer on CPU), and later runs seconds.
root = Path(tempfile.gettempdir()) / 'atlas-p14-l04'
root.mkdir(exist_ok=True)
db = sqlite3.connect(root / 'envelope.sqlite3')
db.execute('CREATE TABLE IF NOT EXISTS jobs (id TEXT PRIMARY KEY, cfg TEXT, state TEXT, result TEXT, error TEXT)')
VERSION = 'markov-v64-familias-v4'
widths = [8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48]
targets = [1e9 * 32 ** (k / 7) for k in range(8)] # cómputo final de ocho duraciones: factor 32
seeds, pilot_seed, lrs = (1, 2, 3), 0, (0.02, 0.04, 0.08, 0.16, 0.32)
def run_job(cfg):
key = hashlib.sha256(json.dumps(cfg, sort_keys=True).encode('utf-8')).hexdigest()
with db:
db.execute("INSERT OR IGNORE INTO jobs VALUES (?, ?, 'pending', NULL, NULL)", (key, json.dumps(cfg)))
db.execute("UPDATE jobs SET state='pending' WHERE id=? AND state IN ('running', 'failed')", (key,))
state, result = db.execute('SELECT state, result FROM jobs WHERE id=?', (key,)).fetchone()
if state == 'done':
return json.loads(result)
with db:
db.execute("UPDATE jobs SET state='running' WHERE id=?", (key,))
try:
out = train_family(cfg['width'], cfg['steps'], cfg['seeds'], cfg['lrs'])
if cfg['kind'] == 'family' and not all(math.isfinite(v) for r in out for v in r['losses']):
raise ValueError(f"pérdida no finita en la familia d={cfg['width']}")
except Exception as exc:
with db:
db.execute("UPDATE jobs SET state='failed', error=? WHERE id=?", (repr(exc), key))
raise
with db:
db.execute("UPDATE jobs SET state='done', result=? WHERE id=?", (json.dumps(out), key))
return out
def horizons(d):
return sorted({max(50, round(c / (6 * n_params(d) * B * T))) for c in targets})
start = time.time()
chosen, results = {}, []
for d in widths:
pilot = run_job(dict(version=VERSION, kind='pilot', width=d, steps=[round(1e10 / (6 * n_params(d) * B * T))],
seeds=[pilot_seed], lrs=list(lrs)))
final = lambda r: r['losses'][-1] if math.isfinite(r['losses'][-1]) else math.inf
chosen[d] = min(pilot, key=final)['lr']
results += run_job(dict(version=VERSION, kind='family', width=d, steps=horizons(d),
seeds=list(seeds), lrs=[chosen[d]]))
print(f'Suelo de entropía de la cadena en evaluación: {floor:.4f}')
print('Tasa elegida por anchura (piloto con semilla 0, presupuesto 1e10):', chosen)
print('Ejecuciones completas:', len(results), '| pasos por anchura:', {d: horizons(d) for d in widths})
print(f'Tiempo de esta celda: {time.time() - start:.0f} s')npm run lab and open the connection link.The reference run yields 243 complete runs and the largest stable rate decreases with width: 0.32 diverges from , and 0.16 already clearly worsens at . The chosen rate oscillates between 0.04 and 0.16 with no clean pattern because near the optimum pilot final losses differ by thousandths: with one pilot seed selection is noisy but loss barely depends on it. Record that limitation: if one size is much worse tuned than its neighbors, it may lose in the envelope because of rate rather than size.
Three design decisions do not copy Hoffmann and should be declared. We use common final budgets instead of per-size horizons so all sizes compete throughout the range. We use eight horizons rather than four because in the stacked family they cost nearly the same and reduce the envelope sawtooth (a later cell checks whether it matters). And the width grid was densified after an initial pass with six widths (8, 12, 16, 24, 32 and 48) where only three sizes won: that extension is exploratory and recorded as such.
Construct the envelope, fit and resample
The next cell applies the definition literally. It averages three seeds for each width and horizon pair; it does not smooth. Over 300 logarithmically spaced budgets in the designed range, to , it interpolates each curve in within support and chooses the lowest loss among at least two candidate sizes. Each winner carries its width, horizon, the fraction of its run traversed and whether it has smaller and larger rivals at that budget.
The fitting rule is fixed before looking at the slope. Take the longest contiguous span of budgets with a bracketed winner, and fit only if it covers at least a factor 10 of compute and three distinct winning sizes; otherwise the result is “not identifiable.” This is an operational rule of this lab, not Hoffmann’s. The interval comes from 200 block resamples: for each width draw three seeds with replacement, each seed carrying all its horizons (paired runs: same initialization and batches), and each replicate rebuilds envelope, span and fit. The 10th and 90th percentiles are reported, as in table 2, only if at least 160 replicates are identifiable.
from collections import Counter
def mean_curves(runs, draw=None):
"""Una curva por (anchura, horizonte): media de las semillas elegidas, con repetición si las hay."""
groups = {}
for r in runs:
copies = 1 if draw is None else draw[r['width']].count(r['seed'])
groups.setdefault((r['width'], r['steps']), []).extend([r] * copies)
return [dict(width=w, n=g[0]['n'], steps=H, c=np.array(g[0]['flops'], float),
loss=np.mean([r['losses'] for r in g], axis=0))
for (w, H), g in groups.items() if g]
def envelope(curves, grid):
"""Para cada presupuesto: la menor pérdida interpolada entre las curvas que lo cubren."""
out = []
for c in grid:
cand = [(float(np.interp(np.log(c), np.log(r['c']), r['loss'])), r) for r in curves
if r['c'][0] <= c <= r['c'][-1]] # solo dentro del soporte: sin extrapolar
sizes = {r['n'] for _, r in cand}
if len(sizes) < 2:
out.append(None)
continue
loss, r = min(cand, key=lambda z: (z[0], z[1]['n'], z[1]['steps']))
out.append(dict(c=float(c), loss=loss, n=r['n'], width=r['width'], steps=r['steps'],
fraction=float(c / r['c'][-1]),
flanked=min(sizes) < r['n'] < max(sizes))) # hay candidatos a ambos lados
return out
def fit(best, lo, hi):
pts = [p for p in best if p is not None and lo <= p['c'] <= hi]
x = np.log([p['c'] for p in pts])
a = np.polyfit(x, np.log([p['n'] for p in pts]), 1)[0]
b = np.polyfit(x, np.log([p['c'] / (6 * p['n']) for p in pts]), 1)[0]
return float(a), float(b), pts
def identified_span(best, grid):
"""Regla fijada antes de ajustar: el mayor tramo contiguo de presupuestos cuyo ganador tiene
candidatos menores y mayores. Se ajusta solo si cubre un factor 10 y al menos tres tamaños ganadores."""
spans, cur = [], []
for i, p in enumerate(best + [None]):
if p is not None and p['flanked']:
cur.append(i)
elif cur:
spans.append(cur)
cur = []
if not spans:
return None
span = max(spans, key=len)
lo, hi = grid[span[0]], grid[span[-1]]
if hi / lo < 10 or len({best[i]['width'] for i in span}) < 3:
return None
return lo, hi
curves = mean_curves(results)
grid = np.geomspace(targets[0], targets[-1], 300) # el rango diseñado de presupuestos finales
best = envelope(curves, grid)
span = identified_span(best, grid)
if span is None:
print('No identificable: el tramo flanqueado no cubre un factor 10 con tres tamaños; no se ajusta.')
else:
lo, hi = span
a, b, pts = fit(best, lo, hi)
late = sum(p['fraction'] >= 0.85 for p in pts)
print(f'Tramo identificado: {lo:.3g} a {hi:.3g} FLOPs (factor {hi / lo:.0f}), {len(pts)} presupuestos')
print('Presupuestos ganados por cada anchura:', dict(sorted(Counter(p['width'] for p in pts).items())))
print(f'Ganadores en el último 15 % de su ejecución: {late} de {len(pts)}')
print(f'Exponentes puntuales: a = {a:.3f}, b = {b:.3f}')
# Remuestreo por bloques: para cada anchura, tres semillas con reposición; cada semilla arrastra
# todos sus horizontes. Cada réplica rehace envolvente, tramo y ajuste.
gen = np.random.default_rng(2026)
reps, invalid = [], 0
for _ in range(200):
draw = {w: [int(s) for s in gen.choice(seeds, size=len(seeds))] for w in widths}
rb = envelope(mean_curves(results, draw), grid)
sp = identified_span(rb, grid)
if sp is None:
invalid += 1
continue
reps.append(fit(rb, *sp)[0])
if len(reps) < 160:
print('Sin intervalo: menos de 160 réplicas identificables de 200.')
else:
p10, p90 = np.percentile(reps, [10, 90])
print(f'Percentiles 10 y 90 de a ({len(reps)} réplicas válidas, {invalid} descartadas): '
f'{p10:.3f} a {p90:.3f}; de b: {1 - p90:.3f} a {1 - p10:.3f}')
print('Hoffmann, enfoque 1: a = 0.50 (0.488 a 0.502). Registro previo: a entre 0.4 y 0.6.')
print('Intervalo completo dentro del rango registrado:', 0.4 <= p10 and p90 <= 0.6)
fig, (ax, bx) = plt.subplots(2, 1, figsize=(8, 7), sharex=True, gridspec_kw=dict(height_ratios=[3, 2]))
for i, w in enumerate(widths):
for j, r in enumerate(sorted((r for r in curves if r['width'] == w), key=lambda r: r['steps'])):
ax.plot(r['c'], r['loss'], color=f'C{i}', alpha=0.6, label=f'd={w}' if j == 0 else None)
ax.plot(r['c'][-1], r['loss'][-1], 'o', color=f'C{i}', ms=3)
valid = [p for p in best if p is not None]
ax.plot([p['c'] for p in valid], [p['loss'] for p in valid], 'k--', lw=2, label='envolvente')
ax.axhline(floor, color='gray', lw=1, ls=':', label='entropía de la fuente')
ax.set(xscale='log', ylim=(floor - 0.05, 2.6), ylabel='pérdida en cadenas reservadas')
ax.legend(ncol=4, fontsize=8)
bx.scatter([p['c'] for p in valid], [p['n'] for p in valid], s=6,
c=['k' if p['flanked'] else 'lightgray' for p in valid])
if span is not None:
xs = np.geomspace(lo, hi, 50)
k = np.exp(np.mean(np.log([p['n'] for p in pts])) - a * np.mean(np.log([p['c'] for p in pts])))
bx.plot(xs, k * xs ** a, 'C3', label=f'a = {a:.2f}')
bx.axvspan(lo, hi, color='C0', alpha=0.08)
bx.legend()
bx.set(xscale='log', yscale='log', xlabel='C, FLOPs (6ND)', ylabel='N ganador')
fig.tight_layout()
fig.savefig(root / 'envelope.png', dpi=120)
plt.close(fig)
(root / 'runs.json').write_text(json.dumps(results), encoding='utf-8')
print('Figura y datos en', root)npm run lab and open the connection link.Results and their meaning
In the reference run, the identified span is the entire designed range, to FLOPs (factor 32), and four widths win: 12, 16, 20 and 24. The slope is , with 10th and 90th percentiles from 0.250 to 0.350 in 196 valid replicates of 200, and by the proxy identity , between 0.650 and 0.750. Optimal size grows considerably more slowly than compute: the winner’s ratio goes from about 13 tokens per parameter at FLOPs to about 48 at . And 99 of 300 winners are in the last 15 % of their run, not all as in Chinchilla: the figure shows why. Just after a horizon ends, the best candidate is an intermediate segment of the run ending at the next budget, whose rate has not fully annealed. This sawtooth is a fingerprint of our design: with common final budgets all endpoints fall at the same eight values, separated by factor , and between two there are only intermediate segments. If in each gap the winning run ends at its end, the fraction of winners in their last 15 % is : exactly the observed 99 of 300. In Hoffmann’s design, with per-size horizons and many sizes, endpoints are distributed along the axis and one is nearly always near each budget, consistent with all their winners falling in the last 15 %.
Against the preregistration, the prediction fails: the entire interval for , 0.250 to 0.350, lies below 0.4. Against the paper, is far from 0.50. We cannot conclude Chinchilla is wrong, because nothing in this system resembles its regime. We can explain the discrepancy with the theorem in the next section: requires the capacity term to fall faster than the data term (), plausible in our task. A transition matrix has only a few thousand useful degrees of freedom: beyond the rank capturing most of its structure, more width helps little, while estimating probabilities well still needs many samples. The final cell tests the explanation and stability of the number.
from scipy.optimize import least_squares
# ¿Sustituye un corte de una ejecución larga al final de una corta? Misma anchura, mismo cómputo.
gaps = []
for w in widths:
cs = sorted((r for r in curves if r['width'] == w), key=lambda r: r['steps'])
for i, short in enumerate(cs):
for long in cs[i + 1:]:
if short['steps'] >= 100:
cut = np.interp(np.log(short['c'][-1]), np.log(long['c']), long['loss'])
gaps.append(cut - short['loss'][-1])
gaps = np.array(gaps)
print(f'Final de la corta mejor que el corte de la larga: {np.sum(gaps > 0)} de {len(gaps)} parejas; '
f'ventaja mediana {np.median(gaps):.3f} nats')
def exponent(runs):
b = envelope(mean_curves(runs), grid)
sp = identified_span(b, grid)
return 'no identificable' if sp is None else round(fit(b, *sp)[0], 3)
order = {w: sorted({r['steps'] for r in results if r['width'] == w}) for w in widths}
print('a con 4 de los 8 horizontes (alternos):',
exponent([r for r in results if order[r['width']].index(r['steps']) % 2 == 1]))
print('a sin la anchura 48:', exponent([r for r in results if r['width'] != 48]))
print('a sin las anchuras 8 y 10:', exponent([r for r in results if r['width'] > 10]))
print('a sin las anchuras 20 y 24:', exponent([r for r in results if r['width'] not in (20, 24)]))
# Comprobación cruzada con el teorema: forma aditiva ajustada a los finales de ejecución (100 pasos o más).
ends = [(r['n'], r['c'][-1] / (6 * r['n']), r['loss'][-1]) for r in curves if r['steps'] >= 100]
n_, d_, l_ = map(np.array, zip(*ends))
res = lambda t: np.log(t[0] + np.exp(t[1]) * n_ ** -t[2] + np.exp(t[3]) * d_ ** -t[4]) - np.log(l_)
E, _, alpha, _, beta = least_squares(res, [1.6, 3, 0.5, 3, 0.4]).x
print(f'Forma aditiva en {len(ends)} finales: E = {E:.3f}, alpha = {alpha:.2f}, beta = {beta:.2f}, '
f'beta/(alpha+beta) = {beta / (alpha + beta):.2f}')npm run lab and open the connection link.The first line directly measures the first common error. In 140 of 160 pairs of same-width runs (the shorter at least 100 steps), the short run’s end is better than the equal-compute point of the long one, with median advantage 0.025 nats: on the order of the difference between neighboring widths in the envelope. Had you trained one long run per size and read intermediate segments, you would systematically have penalized each size at every budget below its horizon, and slope bias would depend on how that penalty varies with size, something you cannot know without the short runs.
Reasonable design variations do not change the conclusion. With only four alternating horizons per width, . Without width 48, which never wins, the result is identical. Without the two smallest widths it is 0.261. The exception is instructive: removing widths 20 and 24, which win most, makes the grid coarse again and raises slope to 0.409, inside the registered range. A poor size grid can “confirm” a prediction by discretization alone; the report must therefore include this sensitivity table, not just the favorite number. Try it in the opening figure with the “Without 20 or 24” button.
The cross-check fits the additive form to the 62 endpoints of runs at least 100 steps long and obtains and : the capacity term indeed falls much faster, and has the same direction of deviation as the envelope. This is not a second independent measurement, because it uses the same runs and another estimator (the third approach, studied in lesson 6), and its falls below the true floor of 1.63, revealing that the additive form does not describe this surface well. This reminds us of the third common error: a fitted is not irreducible loss, and a narrow range does not identify it.
To use your own data, replace source and model but preserve each curve’s contract: parameters under one convention, positive increasing cost, finite loss on a fixed held-out set, and horizon, seed, rate and corpus metadata. Also preserve analysis order: identification and resampling rules fixed before looking, sensitivity table afterward.
Why winners change: a solvable model
A deeper explanation appears if we construct two curves with an explicit capacity-data trade-off. Suppose , and, only for this example, loss for any is
Substituting , the fixed-size curve is . The capacity term favors the large model, while the data term favors the small one at fixed compute: more parameters leave fewer tokens. The difference between large and small is
The first term is negative and the second positive. Since the second strictly decreases as increases, there is one positive crossing:
Below , wins; above it wins. The claim depends on this parametric form and its signs: actual training curves may cross multiple times, be noisy or be undefined over the whole interval. The calculation helps explain how an envelope can change candidates without either size changing value during training.
A verifiable numerical case uses , , and , in consistent arbitrary units. The crossing is . At that point and , and both losses are . For , losses are and ; for they are and . The winner changes because additional budget allows more data for the larger model.
If instead of two sizes we let range over all positive reals, the envelope of the family has closed form, yielding the exponent the first approach tries to measure.
Proof
Write , so and . With , is a sum of two strictly convex exponentials in , hence strictly convex; it tends to as (first term) and as (second). It therefore has a unique minimum, where the derivative vanishes:
Raising to gives , and .
∎The theorem says two useful things for reading the envelope. First, the allocation exponent is not a property of compute but of the ratio between capacity and data exponents: if the data term falls more slowly than capacity (), extra compute should go more to tokens than parameters (). Hoffmann’s parametric fit (, ) gives , near the 0.46 in table 2. Second, a size grid’s discrete envelope is a stepped approximation of : if sizes are separated by factor , the winner can differ from by up to approximately factor , and a regression slope over steps is reliable only when the fitted span covers several winner changes.
This also clarifies a common error: common irreducible loss cancels when comparing models in this example. We cannot therefore ignore it in a regression of loss against compute. If differs between curves because data or metric change, it does not even cancel at the crossing. An envelope is interpretable only when losses belong to a comparable scale and evaluation set.
What the interval actually resamples
Seed resampling answers a specific question: how much would slope change if we repeated the sweep with other initializations and batch orders, keeping the same family, horizons and rates? The resampling unit must therefore be what would be repeated, the seed, and each seed must carry all its horizons because they share initial weights and batches. Resampling the 300 interpolated budgets as independent observations would be a serious error: they are highly correlated readings from a few dozen curves, and the interval would be absurdly narrow. For the same reason each replicate rebuilds the envelope from curves: treating original winners as fixed would hide selection variation, precisely what moves most.
What the interval excludes is equally important. It does not include choice of size grid (in the lab this moves from 0.28 to 0.41), rates, architecture, data source or FLOP convention. With three seeds, each width also admits only 10 distinct combinations of seeds with replacement, and the replicate distribution is coarse; conditioning on identifiable replicates (196 of 200) biases it slightly. The 10th and 90th percentiles describe the central 80 % of that distribution, not a calibrated confidence interval. Hoffmann’s table uses another scheme, 100 resamples of 80 % of the data, with different units and experiment count: comparison of the two bands is conceptual, not numerical.
When comparing with table 2, first declare method, parameter convention, FLOP definition and range; then compare exponents and intervals under their respective conditions, distinguishing a discrepancy from proof of its cause. The lab’s cross-check makes our discrepancy’s explanation plausible, not proven: proving it would require an intervention, for example changing the source to one whose structure is not captured at low rank and checking whether rises. The next lesson studies isoFLOP profiles, which design final runs by budget and fit a parabola of loss against size; preserving this lab’s raw curves will allow both estimators to be compared without retraining.
Exercises
import numpy as np
def loss_envelope(runs, flop_grid):
passThe envelope selects losses among available curves, not among every possible model. Its quality depends on comparable schedules, support without extrapolation, size coverage and resampling that reconstructs selection. When the frontier lies on the edge or uncertainty is not identifiable, the correct result is indeterminate.