Module contents
Stage 2 of 8Research 110 min

Sweep infrastructure and FLOP accounting

Build explicit compute accounting, persistent sweep infrastructure and duration-matched schedules.

After this lesson you can

  • Define the model family and shape rules for depth, width and heads.
  • Implement and verify parameter and FLOP counters with and without embeddings and attention.
  • Build a resumable run queue with complete provenance for every point.
  • Demonstrate experimentally the bias from using a schedule longer than the run.

Before you start

A point on a curve is a complete run

The registered question now needs machinery that produces comparable points. Each point of a scaling law must say which model was trained, on what data, for how many steps, under which schedule and with which compute convention. If two points use different parameter definitions, a power-law fit can discover a difference in accounting rather than a property of training.

There is an economical temptation worth dismantling before writing a line of code. To trace an IsoFLOP profile, each budget CC needs several sizes NN trained with D=C/(6N)D=C/(6N) tokens. It seems cheaper to train each size only once, with a long schedule of horizon DHD_H, and read loss at the intermediate point corresponding to each budget. Kaplan and colleagues (2020) estimated their compute-efficient frontier in a similar way, from training curves with a fixed-length schedule for all models. The problem is that halfway through a cosine the learning rate is still high and loss has not yet received the benefit of final decay: an intermediate reading is not the end of a short run with the same number of tokens.

The figure turns that observation into an explicit model you can manipulate. Loss at the end of a run with a matched schedule follows the parametric form of Hoffmann and colleagues (2022), L∗(N,D)=E+AN−α+BD−βL^*(N,D)=E+AN^{-\alpha}+BD^{-\beta}, with their published constants (E=1.69E=1.69, A=406.4A=406.4, B=410.7B=410.7, α=0.34\alpha=0.34, β=0.28\beta=0.28). Reading at token DD of a run with cosine horizon DHD_H adds excess κ u(r)\kappa\,u(r), where r=D/DHr=D/D_H is the fraction traversed and u(r)=[1+cos⁡(πr)]/2u(r)=[1+\cos(\pi r)]/2 is the fraction of the rate not yet decayed. Excess proportional to uu is a working hypothesis, not a measured law: κ\kappa summarizes the contribution of final decay and you choose it.

InteractiveA schedule for each horizon
  • Matched schedule
  • Long-schedule readout
  • Schedule-matched minimum
  • Interim minimum
  • Schedule-matched N∗N^*
  • Intermediate-read N∗N^*
Top chart
3e19
0.10
30.0 B
Schedule-matched N∗N^*376 M
Intermediate-read N∗N^*202 M
Read fraction rr at the interim minimum0.83
Schedule-matched exponent aa0.452
Intermediate-read exponent aa0.599
Above, the IsoFLOP profile for the chosen budget: blue with a matched schedule, orange reading the long run; dashed verticals mark minima. The “One run” view shows, for the optimal size, the intermediate curve of the long run versus the ends of matched runs. Below, optimal size against budget and fitted exponents. This is a model with stated assumptions, not an experimental result.

Three readings of the figure organize the rest of the lesson.

  1. With κ=0\kappa=0 and a large horizon the two curves coincide and the exponent aa of N∗∝CaN^*\propto C^a is β/(α+β)=0.28/0.62≈0.452\beta/(\alpha+\beta)=0.28/0.62\approx 0.452, the analytical value of Hoffmann’s model.
  2. In the initial state (κ=0.1\kappa=0.1, DH=3×1010D_H=3\times10^{10}) the measured exponent rises to about 0.60. Two mechanisms are involved. At fixed budget, a large model is read earlier in its schedule (r=C/(6NDH)r=C/(6ND_H) decreases with NN), with more rate not yet decayed, and is penalized: the minimum shifts toward smaller models. In addition, left of the point where the orange curve begins, the long run never reached those tokens (r>1r>1), so at large budgets the minimum is forced toward larger models. Both effects tilt the line of N∗N^*.
  3. With DH=1011D_H=10^{11} and the same κ\kappa, truncation disappears and the shift grows with budget: the exponent falls to about 0.38. The sign of the bias depends on the geometry between budgets and horizon.

The real history is more nuanced than the model. Hoffmann and colleagues attributed part of the discrepancy with Kaplan to not matching the schedule to duration. Porian and colleagues (2024) reproduce Kaplan’s result and explain it through three factors: final-layer compute cost, warmup duration and scale-dependent optimizer tuning; they also conclude that careful rate decay is not essential to recovering the Chinchilla law. Pearce and Song (2024) attribute much of the discrepancy to counting parameters without embeddings and working at small scale. None of these explanations can be verified without explicit accounting and recorded schedules: that is what this lesson builds.

A model family before a law

A scaling law compares models in a family, not arbitrary parameter tables. Define width dd, number of blocks ℓ\ell, heads hh, context TT and vocabulary VV. Require dd divisible by hh, so each head has dimension d/hd/h. Here we use an educational family of causal blocks with multi-head attention, fourfold MLP expansion, two normalizations per block and output tied to the token matrix. The output layer reuses the embedding weight: counting it twice would inflate NN although it is used twice in computation.

Shape rules turn a desired size into a feasible configuration. A common choice fixes the aspect ratio and head dimension: d=64ℓd=64\ell and d/h=64d/h=64, so h=ℓh=\ell. With TT, VV, tokenizer and MLP ratio fixed, the family is parameterized by a single integer ℓ\ell and the number of non-embedding parameters grows as ℓd2∝d3\ell d^2\propto d^3. Another policy, fixing hh and letting head dimension grow, also satisfies divisibility but yields a different architecture; it is unwise to fit a slope mixing policies without recording them. The exact count, not nominal size, identifies each point.

For the family used here, without projection biases, each block has four d×dd\times d attention matrices (Q, K, V and output), two MLP matrices d×4dd\times4d and 4d×d4d\times d, and two normalizations with scale and shift of length dd. Thus there are 4d2+8d2+4d=12d2+4d4d^2+8d^2+4d=12d^2+4d parameters per block. Token and position tables contribute Vd+TdVd+Td, and final normalization adds 2d2d:

Ntotal=ℓ(12d2+4d)+Vd+Td+2d.N_{\mathrm{total}}=\ell(12d^2+4d)+Vd+Td+2d.

In the no-embedding convention we use, both tables are excluded and final normalization is retained: Nsin tablas=ℓ(12d2+4d)+2dN_{\mathrm{sin\,tablas}}=\ell(12d^2+4d)+2d. This choice is explicit, not a universal definition. Token-table parameters still participate in output projection because the weight is tied: excluding them from the NN count does not remove their compute cost. Count each unique tensor once; in PyTorch shared parameters are verified by identity, not by summing module names.

A tensor count answers a different question from memory consumption. The same tensor may be stored at one precision for weights and another for optimizer states; gradients and activations add memory. At each end of the family test a forward and backward pass with the intended microbatch and context, measure peak memory and leave margin. Repeat if precision, activation checkpointing or attention implementation changes.

The FLOP accounting convention identifies which operations are included, whether a multiplication and addition count as two FLOPs, whether computation includes backpropagation, how causal attention is treated and which parameters are included in NN. Two figures are comparable only when their conventions match. Transformer accounting provides the context; here we define a verifiable version for a specific implementation.

Why the parameter convention moves the exponent

If loss follows an exact power law in one convention, it stops doing so in the other, and distortion is concentrated in small models. With the rule d=64ℓd=64\ell, Nsin tablas≈12ℓd2=12d3/64N_{\mathrm{sin\,tablas}}\approx 12\ell d^2=12d^3/64, while tables add (V+T)d∝Nsin tablas1/3(V+T)d\propto N_{\mathrm{sin\,tablas}}^{1/3}. With GPT-2 vocabulary (V=50257V=50257) and T=1024T=1024, tables are 94 % of parameters at ℓ=2\ell=2, 51 % at ℓ=8\ell=8 and 6 % at ℓ=32\ell=32.

Proof

Since NtotN_{\mathrm{tot}} is an increasing differentiable function of NneN_{\mathrm{ne}}, we can use log⁡Nne\log N_{\mathrm{ne}} as the variable. On one hand log⁡(L−E)=log⁡A−αlog⁡Nne\log(L-E)=\log A-\alpha\log N_{\mathrm{ne}}, so dlog⁡(L−E)/dlog⁡Nne=−αd\log(L-E)/d\log N_{\mathrm{ne}}=-\alpha. On the other,

dlog⁡Ntotdlog⁡Nne=NneNtot dNtotdNne=Nne+γNembNtot=1−(1−γ)φ,\frac{d\log N_{\mathrm{tot}}}{d\log N_{\mathrm{ne}}}=\frac{N_{\mathrm{ne}}}{N_{\mathrm{tot}}}\,\frac{dN_{\mathrm{tot}}}{dN_{\mathrm{ne}}}=\frac{N_{\mathrm{ne}}+\gamma N_{\mathrm{emb}}}{N_{\mathrm{tot}}}=1-(1-\gamma)\varphi,

which is positive because φ<1\varphi<1 and γ≥0\gamma\ge0. The chain rule gives dlog⁡(L−E)/dlog⁡Ntot=−α/[1−(1−γ)φ]d\log(L-E)/d\log N_{\mathrm{tot}}=-\alpha/[1-(1-\gamma)\varphi]. If φ>0\varphi>0 the denominator is less than one and αtot>α\alpha_{\mathrm{tot}}>\alpha; and as φ→0\varphi\to0 makes the denominator tend to one, αtot→α\alpha_{\mathrm{tot}}\to\alpha.

∎

With γ=1/3\gamma=1/3 and φ=0.94\varphi=0.94, the local exponent with respect to total is 2.72.7 times the true one; with φ=0.06\varphi=0.06, only 4 % larger. A fit over small models mixes those regimes and returns an exponent that does not extrapolate. By symmetry, if the exact law were that of the total, the local exponent with respect to NneN_{\mathrm{ne}} would be smaller than the true one. The proposition does not say which convention is correct: it says that for small models choosing it changes the answer, the central mechanism in Pearce and Song’s analysis.

Derive the count without hiding attention

For a matrix multiplication (m×k)(k×n)(m\times k)(k\times n) we count 2mkn2mkn FLOPs: mknmkn products and approximately as many additions. For a batch BB of sequences of length TT, block projections multiply a BT×dBT\times d matrix by weights of total size 12d212d^2, costing 24BTd224BTd^2: 8BTd28BTd^2 for Q, K, V and output, and 16BTd216BTd^2 for the two MLP matrices. In each head, QK⊤QK\T is a (T×d/h)(d/h×T)(T\times d/h)(d/h\times T) product costing 2T2d/h2T^2d/h, and multiplying attention weights by VV costs the same; summing the hh heads, both together cost 4BT2d4BT^2d. Vocabulary projection adds 2BTdV2BTdV.

Per token, the subset of forward-pass multiplications is

fdelante=24ℓd2+4ℓTd+2dV.f_{\mathrm{delante}}=24\ell d^2 + 4\ell Td + 2dV.

The first term is almost exactly 2Nsin tablas2N_{\mathrm{sin\,tablas}}, the rule of two FLOPs per parameter. The last does not appear in Nsin tablasN_{\mathrm{sin\,tablas}} although it costs real compute: it is the final-layer cost Porian and colleagues identify as one factor in the discrepancy. In a small model with a large vocabulary it dominates the total.

Attention matrices are computed densely and the causal mask is then applied: although the upper half is discarded, this code has multiplied the full matrix. A triangular or fused-attention kernel may perform a different number of operations, and this formula does not measure its real cost. It also excludes embedding lookup, normalizations, softmax, activations, mask, optimizer and memory movement. Without the attention term the function omits only 4ℓTd4\ell Td; it does not exclude Q, K, V and output projections.

The ratio between attention multiplications and attention projections is (4BT2d)/(8BTd2)=T/(2d)(4BT^2d)/(8BTd^2)=T/(2d). With fixed width, as TT grows ignoring attention ceases to be a small approximation. The denominator of that ratio is only the four attention projections, not the entire MLP or vocabulary head; to convert a ratio qq into a fraction of the combined total, calculate q/(1+q)q/(1+q).

The rule C≈6NDC\approx 6ND estimates training, whereas our formula lists a subset of the forward pass. The factor of three between training and forward pass arises because backpropagating through a linear layer performs two products of the same size as the forward one: one for the weight gradient and another for the input gradient. It is not an identity for all operations: the first layer does not need its input gradient, and the optimizer and non-matrix operations also cost compute. Record the analytical counter, what the profiler observes and the proxy used to allocate budgets separately; do not directly compare 6ND6ND with a forward-only measurement.

The PyTorch profiler estimates FLOPs of each supported operator using a formula based on its input shapes; it does not count what hardware executes and assigns zero to unrecognized operators. In the lab we use an implementation with explicit matrix operations and compare only that subset. Agreement within 5 % shows that dimensions and convention match for that example, not that they hold for another architecture or kernel. FLOP utilization also requires measured time and a reference rate; a correct counter does not imply high throughput.

A useful verification has two levels. First compare total parameters with the sum of unique tensor sizes and test several small configurations, changing vocabulary, context, width and depth separately: this detects a position term that grows with TT or a tied output counted twice. Then profile a pass with known dimensions and compare operation categories the profiler declares supported. Relative difference uses the analytical value as denominator. Summing all profiler events includes work the formula excludes; if a fused kernel reports no FLOPs, filtering only multiplications will undercount. In either case the percentage diagnoses the scope of comparison before a model error: do not change a constant to force agreement between numbers measuring different sets.

Lab: counter, family and verification

The first cell calculates parameters and cost per token from configuration. The family is deliberately specific: fourfold MLP, separate token and position tables, tied final layer and biases only in normalizations. The lab uses CPU for a modest, reproducible check; if your GPT differs, adapt the rules and verify again.

[ ]Explicit accountingLocal GPU
def count_params(config, include_embeddings=True):
    d, layers, vocab, context = (config[k] for k in ("d", "layers", "vocab", "context"))
    total = layers * (12*d*d + 4*d) + 2*d
    return total + (vocab*d + context*d if include_embeddings else 0)

def flops_per_token(config, include_attention=True):
    d, layers, vocab, context = (config[k] for k in ("d", "layers", "vocab", "context"))
    return layers * (24*d*d + (4*context*d if include_attention else 0)) + 2*d*vocab

cfg = dict(d=32, layers=2, heads=4, vocab=64, context=16)
assert cfg["d"] % cfg["heads"] == 0
print("Parámetros total / sin tablas:", count_params(cfg), count_params(cfg, False))
print("FLOPs matriciales de avance por token:", flops_per_token(cfg))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The configuration generator applies shape rules, checks divisibility, discards duplicates and sorts by size. It also prints the fraction of parameters in tables and the proposition’s factor 1/(1−23φ)1/(1-\tfrac23\varphi), which says how much a local exponent would be distorted by changing conventions at each size.

[ ]Family generatorLocal GPU
def family(depths, vocab=50257, context=1024, aspect=64, head_dim=64):
    configs = {}
    for layers in depths:
        d = aspect * layers
        assert d % head_dim == 0, (layers, d)
        c = dict(d=d, layers=layers, heads=d // head_dim, vocab=vocab, context=context)
        configs[count_params(c)] = c       # el recuento exacto identifica el punto
    return [configs[n] for n in sorted(configs)]

print(f"{'l':>3} {'d':>5} {'h':>3} {'N total':>14} {'N sin tablas':>14} {'phi':>6} {'factor':>7} {'atención/proy.':>15}")
for c in family([2, 4, 4, 8, 16, 32, 48]):
    total, body = count_params(c), count_params(c, False)
    phi = (total - body) / total
    print(f"{c['layers']:>3} {c['d']:>5} {c['heads']:>3} {total:>14,} {body:>14,} {phi:>6.3f} "
          f"{1 / (1 - 2/3 * phi):>7.3f} {c['context'] / (2 * c['d']):>15.2f}")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The next cell constructs exactly the counted family at toy dimensions, compares parameters with unique tensors and profiles a pass without backpropagation. Attention matrices are dense although their result is masked before softmax. The model is a prototype for checking the rules, not a claim about another GPT’s code.

[ ]Model and multiplication profilerLocal GPU
import math
import torch
from torch import nn
from torch.profiler import profile, ProfilerActivity

torch.set_num_threads(1)

class Block(nn.Module):
    def __init__(self, d, heads):
        super().__init__()
        self.heads = heads
        self.norm1 = nn.LayerNorm(d)
        self.norm2 = nn.LayerNorm(d)
        self.qkv = nn.Linear(d, 3*d, bias=False)
        self.out = nn.Linear(d, d, bias=False)
        self.up = nn.Linear(d, 4*d, bias=False)
        self.down = nn.Linear(4*d, d, bias=False)

    def forward(self, x):
        b, t, d = x.shape
        q, k, v = self.qkv(self.norm1(x)).chunk(3, dim=-1)
        def heads(z):
            return z.view(b, t, self.heads, d // self.heads).transpose(1, 2)
        q, k, v = heads(q), heads(k), heads(v)
        scores = q @ k.transpose(-2, -1) / math.sqrt(d // self.heads)
        mask = torch.ones(t, t, dtype=torch.bool, device=x.device).triu(1)
        a = scores.masked_fill(mask, float("-inf")).softmax(dim=-1)
        z = (a @ v).transpose(1, 2).contiguous().view(b, t, d)
        x = x + self.out(z)
        return x + self.down(torch.relu(self.up(self.norm2(x))))

class TinyGPT(nn.Module):
    def __init__(self, c):
        super().__init__()
        self.tok = nn.Embedding(c["vocab"], c["d"])
        self.pos = nn.Embedding(c["context"], c["d"])
        self.blocks = nn.ModuleList([Block(c["d"], c["heads"]) for _ in range(c["layers"])])
        self.final = nn.LayerNorm(c["d"])

    def forward(self, ids):
        t = ids.shape[1]
        x = self.tok(ids) + self.pos(torch.arange(t, device=ids.device))
        for block in self.blocks:
            x = block(x)
        return self.final(x) @ self.tok.weight.T

model = TinyGPT(cfg)
actual = sum(p.numel() for p in model.parameters())   # parameters() no repite tensores compartidos
assert actual == count_params(cfg), (actual, count_params(cfg))
ids = torch.zeros((2, cfg["context"]), dtype=torch.long)
with torch.no_grad(), profile(activities=[ProfilerActivity.CPU], with_flops=True) as prof:
    model(ids)
measured = sum(event.flops for event in prof.key_averages()
               if event.key in ("aten::mm", "aten::bmm", "aten::addmm"))
expected = 2 * cfg["context"] * flops_per_token(cfg)
relative = abs(measured - expected) / expected
print("FLOPs perfilados / previstos:", measured, expected)
print("Diferencia relativa:", round(relative, 6))
assert relative <= 0.05, "Comprueba qué operaciones cuenta tu versión del perfilador"
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In this PyTorch version agreement is exact: the four projections and two attention products of each block, and the final projection, reach the profiler as mm or bmm, which counts 2mkn2mkn like us. If the assertion fails in another version, inspect events and their formulas before changing the counter; an operation unrecognized by the profiler does not mean zero cost. For a model with biases or untied embeddings change both counter and model and check again.

To use this counter in a sweep, multiply cost per token by processed tokens only if context and batch shape match the formula. Different-length sequences and incomplete final batches require summing by shape, because 4ℓTd4\ell Td depends on actual length. With gradient accumulation, optimizer step count alone does not determine tokens: it depends on the number of microbatches and their sizes. Those fields must be in the resolved configuration.

A queue that preserves provenance

Sweep infrastructure turns a grid of configurations and seeds into identifiable jobs, records their status and preserves results with provenance. It builds on configuration management, local sweeps and run provenance. A stable key is calculated over a canonical representation including configuration, seed, data identity and code version. Saving only loss makes it impossible to know whether two points are comparable.

The minimum states are pending, running and finished, with failed attempts recorded. In a single process, on restart after checking that the previous worker no longer exists, interrupted jobs return to pending and finished jobs are not repeated. Transition and result must be committed in a transaction. With multiple workers this policy needs leases and ownership checks: indiscriminately resetting another process’s jobs would cause duplicates.

An interrupted job cannot always resume from the same point. For exact resumption save weights, optimizer, schedule, step, random generator states, data-loader position and order, and precision metadata. Saving weights alone permits continuation, but does not guarantee the same trajectory. Write the checkpoint atomically and preserve configuration and library versions. Data origin, including the token shard scheme if used, must allow reconstruction of what was read.

The following example uses a temporary SQLite file and workers in separate processes that train this lab’s minimal model. One exits abruptly after an update. The main connection closes and reopens before recovering the job, which restarts from the beginning with a new attempt. The key comes from sorted JSON: do not use Python’s hash function, randomized per process and not a stable identity.

[ ]Queue and stable keyLocal GPU
import json
import hashlib
import sqlite3
import os
import subprocess
import sys
import tempfile
import inspect
from pathlib import Path

def run_key(config):
    payload = json.dumps(config, sort_keys=True, separators=(",", ":"), allow_nan=False)
    return hashlib.sha256(payload.encode("utf-8")).hexdigest(), payload

jobs = [dict(config=cfg, seed=seed, dataset="secuencia-periodica-v1",
             code="tiny-gpt-demo-v1", steps=2, lr=0.003)
        for seed in (1, 2)]
worker = """
import json, math, os, sqlite3, sys
import torch
from torch import nn
import torch.nn.functional as F
""" + "class Block(nn.Module):\n" + inspect.getsource(Block.__init__) + inspect.getsource(Block.forward) + "\n" + \
"class TinyGPT(nn.Module):\n" + inspect.getsource(TinyGPT.__init__) + inspect.getsource(TinyGPT.forward) + """
torch.set_num_threads(1)
path, key, mode = sys.argv[1:]
db = sqlite3.connect(path)
with db:
    changed = db.execute("UPDATE runs SET state='running' WHERE id=? AND state='pending'", (key,)).rowcount
    if changed:
        cursor = db.execute("INSERT INTO attempts (run_id, state) VALUES (?, 'running')", (key,))
        attempt = cursor.lastrowid
if not changed:
    db.close()
    sys.exit(0)
job = json.loads(db.execute("SELECT config FROM runs WHERE id=?", (key,)).fetchone()[0])
c = job["config"]
torch.manual_seed(job["seed"])
net = TinyGPT(c)
opt = torch.optim.AdamW(net.parameters(), lr=job["lr"])
seq = torch.arange(c["context"] + 1).unsqueeze(0) % c["vocab"]
inputs, targets = seq[:, :-1], seq[:, 1:]
for step in range(job["steps"]):
    opt.zero_grad()
    loss = F.cross_entropy(net(inputs).reshape(-1, c["vocab"]), targets.reshape(-1))
    loss.backward()
    opt.step()
    if mode == "interrupt" and step == 0:
        os._exit(0)
with torch.no_grad():
    value = F.cross_entropy(net(inputs).reshape(-1, c["vocab"]), targets.reshape(-1)).item()
with db:
    db.execute("UPDATE runs SET state='done', loss=? WHERE id=?", (value, key))
    db.execute("UPDATE attempts SET state='done' WHERE id=?", (attempt,))
db.close()
"""
with tempfile.TemporaryDirectory() as temp:
    path = str(Path(temp) / "runs.sqlite3")
    db = sqlite3.connect(path)
    db.execute("CREATE TABLE runs (id TEXT PRIMARY KEY, config TEXT NOT NULL, state TEXT NOT NULL, loss REAL)")
    db.execute("CREATE TABLE attempts (id INTEGER PRIMARY KEY, run_id TEXT NOT NULL, state TEXT NOT NULL)")
    with db:
        for job in jobs:
            key, payload = run_key(job)
            db.execute("INSERT OR IGNORE INTO runs VALUES (?, ?, 'pending', NULL)", (key, payload))
    db.close()
    first = run_key(jobs[0])[0]
    interrupted = run_key(jobs[1])[0]
    subprocess.run([sys.executable, "-c", worker, path, first, "complete"], check=True,
                   env={**os.environ, "PYTHONUTF8": "1"})
    subprocess.run([sys.executable, "-c", worker, path, interrupted, "interrupt"], check=True,
                   env={**os.environ, "PYTHONUTF8": "1"})
    db = sqlite3.connect(path)
    assert db.execute("SELECT state FROM runs WHERE id=?", (interrupted,)).fetchone()[0] == "running"
    with db:
        db.execute("UPDATE attempts SET state='interrupted' WHERE run_id=? AND state='running'", (interrupted,))
        db.execute("UPDATE runs SET state='pending' WHERE state='running'")
        for job in jobs:
            key, payload = run_key(job)
            db.execute("INSERT OR IGNORE INTO runs VALUES (?, ?, 'pending', NULL)", (key, payload))
    first_result = db.execute("SELECT state, loss FROM runs WHERE id=?", (first,)).fetchone()
    assert first_result[0] == "done" and first_result[1] is not None
    assert db.execute("SELECT state FROM runs WHERE id=?", (interrupted,)).fetchone()[0] == "pending"
    # El mismo reclamo condicional no reclama el terminado.
    with db:
        claimed = db.execute("UPDATE runs SET state='running' WHERE id=? AND state='pending'", (first,)).rowcount
    assert claimed == 0
    db.close()
    # El interrumpido empieza un nuevo intento desde el inicio.
    subprocess.run([sys.executable, "-c", worker, path, interrupted, "complete"], check=True,
                   env={**os.environ, "PYTHONUTF8": "1"})
    db = sqlite3.connect(path)
    print("Estados:", db.execute("SELECT state, COUNT(*) FROM runs GROUP BY state").fetchall())
    print("Intentos:", db.execute("SELECT state, COUNT(*) FROM attempts GROUP BY state ORDER BY state").fetchall())
    assert db.execute("SELECT COUNT(*) FROM runs WHERE state='done'").fetchone()[0] == 2
    assert db.execute("SELECT state, loss FROM runs WHERE id=?", (first,)).fetchone() == first_result
    assert db.execute("SELECT COUNT(*) FROM attempts WHERE run_id=?", (first,)).fetchone()[0] == 1
    assert db.execute("SELECT COUNT(*) FROM attempts WHERE run_id=?", (interrupted,)).fetchone()[0] == 2
    db.close()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The test reopens a real file after abrupt exit during training: it preserves the completed result, records one interrupted attempt and one completed attempt, and checks that reinserting the grid (INSERT OR IGNORE on the key) does not duplicate jobs. The second attempt starts from the initial seed; a checkpoint is not tested. Claiming is atomic because condition state='pending' and the state change occur in the same statement, and rowcount says whether this worker won.

Consider three failure moments. If the process dies before claiming, the job remains pending. If it dies after claiming but before saving a checkpoint, restart the attempt from the beginning or declare it failed. If it dies after writing results but before marking the row finished, recovery must recognize the complete artifact to avoid duplication or produce a new attempt with a different identity. SQLite’s transaction protects its rows but does not make external file writes atomic: “exactly once” requires a strategy for artifacts, not just a flag.

For that last case, write each artifact to a temporary path within the attempt directory, close it, verify its contents and rename it to its final name. Save its hash and path in the transaction marking the result. Recovery validates that the artifact exists and its hash matches; otherwise record the incident and retry under the declared policy. Robustness also depends on the filesystem and data synchronization, so test real interruptions in the environment you will use.

Saved configuration must not depend on implicit library defaults: save the resolved configuration, including effective batch and optimizer parameters, and a schema version. A data identity must identify corpus, splits and tokenizer revision; a path can point to different content tomorrow. The configuration hash identifies data only if the description includes a verifiable fingerprint of those data.

Match the schedule to duration

Matching the schedule to duration defines for each run a warmup and decay whose horizon corresponds to planned steps. For 0≤t≤H0\le t\le H and no warmup, the cosine is η(t)=ηmax⁡[1+cos⁡(πt/H)]/2\eta(t)=\eta_{\max}[1+\cos(\pi t/H)]/2: at t=H/2t=H/2 it is still half the maximum rate and at t=Ht=H it reaches zero. If a long run uses cosine to HH and is read at s<Hs<H, its rate there is ηmax⁡u(s/H)\eta_{\max}u(s/H), not the end of a schedule with horizon ss, which would be zero. Comparing the two losses mixes budget effects with optimization state.

Why does the rate at reading time matter? With stochastic gradients, iterates do not settle at a minimum but fluctuate around it with amplitude increasing with rate; final decay reduces that fluctuation and loss drops visibly in the last steps. Thus the benefit of decay depends on gradient noise: in a deterministic noiseless problem a high rate for longer may simply be better.

The initial figure quantifies how such an excess moves an optimum. Let x=log⁡Nx=\log N and f(x)f(x) be the IsoFLOP profile with matched schedule, with minimum x∗x^* and f′′(x∗)>0f''(x^*)>0 (in Hoffmann’s model, f′′=α2AN−α+β2BD−β>0f''=\alpha^2AN^{-\alpha}+\beta^2BD^{-\beta}>0). The intermediate reading adds κg(x)\kappa g(x), with g(x)=u(r)g(x)=u(r) and r=C/(6DHex)r=C/(6D_He^x). If ff and gg are twice differentiable, the implicit function theorem applied to f′(x)+κg′(x)=0f'(x)+\kappa g'(x)=0 gives the perturbed minimum

xκ∗=x∗−κ g′(x∗)f′′(x∗)+O(κ2),g′(x)=π2 rsin⁡(πr) ≥0.x^*_\kappa=x^*-\kappa\,\frac{g'(x^*)}{f''(x^*)}+O(\kappa^2),\qquad g'(x)=\frac{\pi}{2}\,r\sin(\pi r)\ \ge 0 .

The derivative follows from dr/dx=−rdr/dx=-r and u′(r)=−π2sin⁡(πr)u'(r)=-\tfrac{\pi}{2}\sin(\pi r). Since g′≥0g'\ge0, the intermediate reading shifts the optimum toward smaller models, more so the closer the minimum is to r=1/2r=1/2. If excess were the same for all sizes in the profile (g′≡0g'\equiv0), minima would not move: what shifts the optimum is not bias magnitude but its variation along the profile. The exponent changes only if the shift varies with budget. With C=1019C=10^{19}, DH=1011D_H=10^{11} and κ=0.01\kappa=0.01 the formula predicts Δx=−0.00212\Delta x=-0.00212 and exact minimization gives −0.00213-0.00213.

Two alternatives avoid the problem. The direct one is to train each point with its own cosine, multiplying cost. Hägele and colleagues (2024) propose a constant rate with final cooldown: one long constant-rate run serves multiple durations by launching short cooldowns from its checkpoints, and they show it scales predictably and similarly to cosine. In both cases the point is read at the end of a decay matched to its duration.

Controlled horizon experiment

To give decay something to do, the experiment uses irreducibly noisy data: Markov-chain sequences over the toy model’s 64 tokens, with fixed random transitions. Minimum achievable loss is the exact predictor’s cross-entropy on the evaluation set, so we measure excess over that floor. Each batch is a fresh sample of windows, making the gradient stochastic. The maximum rate is selected before comparison, as in a real study: the best of {0.01,0.03,0.05}\{0.01, 0.03, 0.05\} for the matched short schedule. The cell takes about a minute on CPU.

[ ]Noisy data and rate selectionLocal GPU
import torch.nn.functional as F

V, T = cfg["vocab"], cfg["context"]
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(512, 2048, seed=1)       # cadenas de entrenamiento
held = chains(1024, T + 1, seed=2)     # evaluación: cadenas nuevas
floor = -torch.log(P[held[:, :-1], held[:, 1:]]).mean().item()

def evaluate(net):
    with torch.no_grad():
        return F.cross_entropy(net(held[:, :-1]).reshape(-1, V), held[:, 1:].reshape(-1)).item()

def train(horizon, steps, seed, peak, batch=16, warmup=20, every=0):
    torch.manual_seed(seed)
    net = TinyGPT(cfg)
    opt = torch.optim.AdamW(net.parameters(), lr=peak, weight_decay=0.0)
    gen = torch.Generator().manual_seed(1000 + seed)   # mismos lotes con cualquier horizonte
    curve = []
    for step in range(steps):
        scale = min(1.0, (step + 1) / warmup) * (1 + math.cos(math.pi * step / horizon)) / 2
        for group in opt.param_groups:
            group["lr"] = peak * scale
        rows = torch.randint(pool.shape[0], (batch,), generator=gen)
        cols = torch.randint(pool.shape[1] - T, (batch,), generator=gen)
        x = pool[rows[:, None], cols[:, None] + torch.arange(T + 1)]
        loss = F.cross_entropy(net(x[:, :-1]).reshape(-1, V), x[:, 1:].reshape(-1))
        opt.zero_grad()
        loss.backward()
        opt.step()
        if every and (step + 1) % every == 0:
            curve.append((step + 1, evaluate(net) - floor))
    return evaluate(net) - floor, curve

STEPS = 1200
grid = {peak: train(STEPS, STEPS, seed=0, peak=peak)[0] for peak in (0.01, 0.03, 0.05)}
peak = min(grid, key=grid.get)
print("Pérdida del predictor exacto:", round(floor, 4))
print("Exceso final con calendario ajustado, por tasa:", {k: round(v, 4) for k, v in grid.items()})
print("Tasa elegida:", peak)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Now each seed produces one long run with horizon 3×12003\times1200 steps, evaluated every 100 steps through step 1200, and three matched runs of 400, 800 and 1200 steps. Pairs share seed, initialization and the same batch sequence; only cosine horizon changes. Warmup of 20 steps is identical for all. Results are saved as JSON and the figure is reconstructed from that file, without retraining. It takes a couple of minutes.

[ ]Intermediate reading versus matched schedulesLocal GPU
import matplotlib.pyplot as plt

reads, seeds = (400, 800, STEPS), (0, 1, 2)
rows, curves = [], {}
for seed in seeds:
    _, curve = train(3 * STEPS, STEPS, seed, peak, every=100)
    curves[seed] = curve
    at = dict(curve)
    for s in reads:
        matched = grid[peak] if (seed == 0 and s == STEPS) else train(s, s, seed, peak)[0]
        rows.append(dict(seed=seed, step=s, read=at[s], matched=matched, diff=at[s] - matched))

print("semilla  pasos  exceso leído  exceso ajustado  diferencia")
for r in rows:
    print(f"{r['seed']:>7} {r['step']:>6} {r['read']:>13.4f} {r['matched']:>16.4f} {r['diff']:>11.4f}")
for s in reads:
    diffs = [r["diff"] for r in rows if r["step"] == s]
    print(f"Paso {s}: diferencia media {sum(diffs) / len(diffs):.4f}, positivas {sum(d > 0 for d in diffs)} de {len(diffs)}")

out = Path(tempfile.gettempdir()) / "atlas-p14-l02"
out.mkdir(exist_ok=True)
record = dict(config=cfg, data="markov-v64-escala3-semilla0", floor=floor, peak_grid=grid, peak=peak,
              schedule="coseno con 20 pasos de calentamiento lineal", long_horizon=3 * STEPS,
              seeds=list(seeds), rows=rows, curves={str(k): v for k, v in curves.items()},
              torch=torch.__version__)
(out / "calendarios.json").write_text(json.dumps(record, indent=2), encoding="utf-8")

saved = json.loads((out / "calendarios.json").read_text(encoding="utf-8"))
fig, ax = plt.subplots(figsize=(7, 4))
for i, (seed, curve) in enumerate(saved["curves"].items()):
    xs, ys = zip(*curve)
    ax.plot(xs, ys, color="C1", alpha=0.8, label="Ejecución larga, lectura intermedia" if i == 0 else None)
for i, r in enumerate(saved["rows"]):
    ax.scatter([r["step"]], [r["matched"]], color="C0", zorder=3,
               label="Final de ejecución ajustada" if i == 0 else None)
ax.set(xlabel="Pasos (16 secuencias de 16 tokens por paso)", ylabel="Exceso sobre el predictor exacto (nats)",
       yscale="log", title=f"Tasa máxima {saved['peak']}, horizonte largo {saved['long_horizon']}")
ax.legend()
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.

The last step of each run uses the rate at step H−1H-1, because updates are zero-indexed, and evaluation occurs after the final update. With the chosen rate (0.03), at steps 800 and 1200 the matched run ends below the intermediate reading for all three seeds, with mean differences of 0.032 and 0.036 nats; at step 1200 this is about 40 % of the matched run’s excess over the floor. At step 400 the opposite occurs for all three seeds (mean difference −0.038-0.038): at that stage the model still progresses quickly, loss is dominated by what remains to be learned rather than fluctuation, and decaying the rate so early cuts learning more than it reduces noise. Intermediate-reading bias is not a fixed shift: its sign changes with training phase, and its magnitude depends on rate (in earlier tests of this configuration, at 0.01 it almost disappeared at step 1200 and at 0.05 it was several times larger), exactly the role of κ\kappa in the figure. The figure’s assumption of always-positive excess κu(r)\kappa u(r) describes the noise-dominated phase; this cell shows it does not hold early in training, and that a bias model must be validated against actual runs before correcting points.

The paired design reduces one source of variation because both trajectories start with the same weights and see the same batches; but three seeds do not represent the initialization distribution. In a research comparison fix seeds and rates before looking at results, report each pair’s difference at the same evaluation point and do not treat successive steps of one trajectory as independent replicates. Studying exponent bias requires many sizes and budgets, not one comparison; this cell establishes that the effect exists under your conditions and its magnitude.

What to save and how to diagnose

For each run persist resolved configuration, seed, code and dependency versions, corpus identifier and split, tokenizer, architecture and parameter convention, context length, effective batch, precision, full schedule with horizon and warmup, and schedule fraction at each evaluation. Save losses by evaluation step, processed tokens, estimated FLOPs under the chosen convention together with separate terms (24ℓd224\ell d^2, 4ℓTd4\ell Td, 2dV2dV), duration, hardware, checkpoint paths and hashes, errors and retries. This lets you redo any fit under another convention without retraining.

An outlier requires investigation before exclusion. Check for numerical overflow, precision change, corrupt data, interruption or a misconfigured rate. Keep the row and reason for any exclusion, together with results with and without it. Do not use a point’s appearance as the sole justification after seeing the curve: register exclusion rules in advance and distinguish exploratory analysis.

The verifiable result of the complete work is: a counter for your architecture checked against the relevant profiler subset within 5 %, a persistent queue that resumes after a real interruption without repeating completed runs, and a schedule comparison with saved data and a regenerable chart in which, during late training, the long run’s intermediate reading is above the matched short run’s end at the same token count for every seed. Abrupt exit of a test worker does not substitute for a checkpoint interruption in your real training.

Exercises

NumericThe weight of attention
For dense attention with d=256d=256 and T=1024T=1024, count 4T2d4T^2d FLOPs for QK⊤QK\T and the product by VV, and 8Td28Td^2 for the four Q, K, V and output projections. What fraction of the combined cost of both components corresponds to QK⊤QK\T and the product by VV? Enter a number between 0 and 1.
NumericA distorted exponent
A family uses d=64ℓd=64\ell, V=50257V=50257 and T=1024T=1024, and loss follows exactly E+ANne−αE+AN_{\mathrm{ne}}^{-\alpha} in parameters without tables. For the model with ℓ=4\ell=4, by what factor is the local exponent measured relative to total parameters multiplied? Use Nne=ℓ(12d2+4d)+2dN_{\mathrm{ne}}=\ell(12d^2+4d)+2d, Nemb=(V+T)dN_{\mathrm{emb}}=(V+T)d and γ=1/3\gamma=1/3.
QuizA convention that changes the slope
Two teams fit L−E∝N−αL-E\propto N^{-\alpha} on the same models, one using total parameters and the other excluding embedding tables. At what size range will their exponents differ most and why?
QuizWhich way does the optimum move?
In the IsoFLOP profile of a budget CC, all sizes are read from runs with the same horizon DHD_H and the minimum lies in a region where 0<r<10<r<1. According to the lesson's first-order expansion, what happens to the measured optimal size?
QuizRedo an analysis
After the sweep you decide the exponent should be fitted with total parameters and FLOPs including attention, instead of the original convention. What per-run record lets you redo it without retraining?
CodeCount an explicit family
Implement count_params(c, include_embeddings) and flops_per_token(c, include_attention) for the described family: blocks with 12d²+4d parameters, Vd and Td tables, final normalization 2d and forward FLOPs 24ℓd² + 4ℓTd + 2dV. The embedding option removes both tables; the attention option controls only the 4ℓTd term. Tests compare against tensor-by-tensor counts.
def count_params(c, include_embeddings=True):
  pass

def flops_per_token(c, include_attention=True):
  pass
Shift+Enter to run
Key idea

A scaling-law point is a complete run with its compute convention, schedule and provenance. Counting or excluding embedding tables changes the local exponent by a factor 1/(1−(1−γ)φ)1/(1-(1-\gamma)\varphi), large for small models; the final layer costs 2dV2dV FLOPs per token even when absent from NN. Reading midway through a long schedule adds excess that varies along the profile and shifts the optimum; what is measured at the end of a matched decay does not have that bias. The resumable queue and primary-data record allow any analysis to be redone without retraining.