Module contents
Stage 7 of 8Research 90 min

Validating with a preregistered extrapolation

Preregister and evaluate an out-of-range scaling-law prediction.

After this lesson you can

  • Choose a validation run and register its prediction and interval before training.
  • Propagate uncertainty from the three approaches into the prediction.
  • Execute validation with exactly the same pipeline.
  • Evaluate the prediction against the registered criterion and discuss the result.

Before you start

The prediction you have not seen yet

A scaling law is fitted to make a decision that cannot yet be measured. Hoffmann and colleagues did more than describe their 400-plus training runs: they used all three approaches to set the optimal size at Gopher’s budget and trained Chinchilla, with 70 000 million parameters and four times more data than Gopher (280 000 million), at the same compute. Chinchilla performed better on almost all evaluations. That run was the test that gave the paper credibility: a prediction made before seeing the result, at a scale no study run had reached.

Fitting a law answers a retrospective question, “what shape describes these measurements?” Validating it answers a prospective one, “what loss will a run that does not yet exist obtain?” A smooth curve can pass through all known points and fail precisely where we want to use it; the only way to find out without fooling ourselves is to fix configuration, prediction, uncertainty and criterion before training. In this lesson we actually do so: using the 105 training runs from isoFLOP profiles, we register predictions of all three approaches for a run with ten times the largest budget, train it on the RTX 4060 and evaluate using the rule we wrote.

InteractivePrediction versus reality
2.302.322.342.372.402.4510¹¹10¹²10¹³end of fitCompute budget C in FLOPs (log scale)Loss in nats (log scale of L − 2.2497)
  • Parametric surface: bootstrap median
  • Mean band (dark) and prediction band (light), 5th–95th percentiles
  • Envelope
  • IsoFLOP profiles
  • Profile minimum (filled: fitted; hollow: held out)
  • Held-out run at 8·10¹² FLOPs
Approach
Budgets in the fit
Preregistered prediction2.3506
Predictive interval, 5th to 95th percentile2.3488 to 2.3520
Observed (mean of 3 seeds)2.3361
Error Ŷ − Y+0.0144
Criterion |Y − Ŷ| ≤ 0.005misses
Y within the intervalno
Actual data: 35 p14-l05 configurations with three seeds (gray points: configuration means) and the held-out run at 8×10¹² FLOPs (orange). Curves follow each fit's allocation law; the vertical marker is the prediction for the configuration actually trained. The vertical axis shows loss minus source entropy on a logarithmic scale, so extrapolation differences are visible at scale.

The initial state shows the parametric surface with all five budgets: its band is narrow and the orange point is clearly below. Switch to profiles and envelope: the three predictions differ by about 0.013 nats, more than ten times the dispersion of a three-seed mean, so they cannot all be right at once. Then reduce to three budgets. Profile and envelope bands widen greatly away from the last observation, as the next section’s theorem predicts, while the surface band remains narrow and its error grows as fewer budgets enter the fit. A narrow band is not a reliable prediction: it only says seed noise barely moves the fit.

What it means to predict outside support

“Outside support” does not merely mean “a bigger number.” Development data occupy a region of configuration space: sizes, tokens, budget, architecture, context length, distribution and schedule. In p14-l05 the largest budget is 8⋅10118\cdot10^{11} FLOPs, the largest model has 121 257 parameters and the longest run processes 12.2 million tokens. Our held-out run, with 72 897 parameters and 18.3 million tokens, is within size range but outside token and budget ranges. Always plot the new configuration in the (log⁡N,log⁡D)(\log N,\log D) plane alongside the previous ones: large distance in one dimension is not offset by closeness in another.

With C≈6NDC\approx 6ND, multiplying CC by ten permits many combinations. Record whether “ten times larger” means FLOPs, parameters or tokens, and calculate the ratio with the counter defined in the accounting lesson: our effective 6ND6ND is 7.999⋅10127.999\cdot10^{12}, because tokens are rounded to whole steps of 2048.

Extrapolation does not test a law in every regime. One held-out observation checks a particular configuration, architecture, distribution and schedule; a fit may succeed there through compensating errors or fail because the pipeline changed. Out-of-distribution generalization adds another layer: a fit on English text loss does not predict code or another language, and changing tokenizer makes per-token loss incomparable because the information unit changed. Keep evaluation set and metric fixed, or formulate a second hypothesis for the new domain.

Before spending the large budget, rehearse the procedure with forward validation in scale: order budgets, fit on smaller ones and predict the next, without a held-out budget influencing that round’s fit or model selection. The split must respect dependencies: checkpoints from one run, or configurations sharing a seed and corpus, go together on one side. This measures how the procedure extrapolates two or four times; it does not prove the error holds at ten.

Also compare with a simple baseline fixed in advance. The toughest is “no improvement”: predict the best development loss for the large run, here 2.3830. A law that does not clearly beat that baseline has demonstrated nothing, so our criterion tolerance is fixed relative to predicted improvement, not absolute loss level.

Why bands widen when extrapolating

The interactive’s band behavior has an exact explanation in the simplest case: a least-squares line on log scale, such as allocation law ln⁡N∗=aln⁡C+b\ln N_\ast=a\ln C+b or a linearized loss frontier.

Proof

The normal equations give θ^1=∑i(xi−xˉ)yi/Sxx\hat\theta_1=\sum_i(x_i-\bar x)y_i/S_{xx} and θ^0=yˉ−θ^1xˉ\hat\theta_0=\bar y-\hat\theta_1\bar x, so y^(x0)=yˉ+θ^1(x0−xˉ)\hat y(x_0)=\bar y+\hat\theta_1(x_0-\bar x). Since Var⁡yi=σ2\operatorname{Var}y_i=\sigma^2 and the yiy_i are uncorrelated, Var⁡yˉ=σ2/n\operatorname{Var}\bar y=\sigma^2/n and Var⁡θ^1=σ2∑i(xi−xˉ)2/Sxx2=σ2/Sxx\operatorname{Var}\hat\theta_1=\sigma^2\sum_i(x_i-\bar x)^2/S_{xx}^2=\sigma^2/S_{xx}. Also Cov⁡(yˉ,θ^1)=σ2nSxx∑i(xi−xˉ)=0\operatorname{Cov}(\bar y,\hat\theta_1)=\frac{\sigma^2}{nS_{xx}}\sum_i(x_i-\bar x)=0. Adding, Var⁡y^(x0)=σ2/n+(x0−xˉ)2σ2/Sxx\operatorname{Var}\hat y(x_0)=\sigma^2/n+(x_0-\bar x)^2\sigma^2/S_{xx}. For the new observation, y0−y^(x0)=ε0+(θ0+θ1x0−y^(x0))y_0-\hat y(x_0)=\varepsilon_0+(\theta_0+\theta_1x_0-\hat y(x_0)), and ε0\varepsilon_0 is uncorrelated with y^(x0)\hat y(x_0), which depends only on ε1,…,εn\varepsilon_1,\dots,\varepsilon_n; variances add and the σ2\sigma^2 term appears.

∎

Variance grows quadratically with distance from the data center, measured in units of their spread. Our development budgets are 5⋅1010⋅2u5\cdot10^{10}\cdot2^u with u=0,…,4u=0,\dots,4, and the held-out one is at u0=log⁡2160≈7.32u_0=\log_2 160\approx7.32. Then uˉ=2\bar u=2, Suu=10S_{uu}=10 and prediction standard deviation there is 1+n(u0−uˉ)2/Suu≈3.9\sqrt{1+n(u_0-\bar u)^2/S_{uu}}\approx3.9 times that at the range center. The ratio is independent of log base. Thus extrapolating several orders of magnitude from a one- or two-decade range is only as good as the functional form supporting it.

The theorem assumes a correct model. When it is not correct, bias appears that no resampling detects. Suppose truth has curvature f(x)=θ0+θ1x+κ(x−xˉ)2f(x)=\theta_0+\theta_1x+\kappa(x-\bar x)^2 and the design is symmetric, ∑i(xi−xˉ)3=0\sum_i(x_i-\bar x)^3=0. The fitted line has expected slope θ1+κ∑i(xi−xˉ)3/Sxx=θ1\theta_1+\kappa\sum_i(x_i-\bar x)^3/S_{xx}=\theta_1 and passes through xˉ\bar x at height fˉ=θ0+θ1xˉ+κSxx/n\bar f=\theta_0+\theta_1\bar x+\kappa S_{xx}/n, so bias at x0x_0 is κ (Sxx/n−(x0−xˉ)2)\kappa\,(S_{xx}/n-(x_0-\bar x)^2). Inside the range bias is small and of one sign; outside it grows quadratically and changes sign. In our design it is 2κ2\kappa at the center and −26.3κ-26.3\kappa at the held-out point: curvature invisible in development residuals is multiplied thirteenfold when extrapolating.

This is the structural weakness of bootstrap intervals: they resample noise, the variance term, but inherit shape bias intact. Besiroglu and colleagues showed this with Chinchilla itself: published parametric-fit intervals were so narrow that about 600 000 training runs would be needed to obtain them, when the study had between 400 and 500 points, and refitting extracted data gave E=1.82E=1.82, A=482.01A=482.01, B=2085.43B=2085.43, α=0.348\alpha=0.348 and β=0.366\beta=0.366 versus original E=1.69E=1.69, A=406.4A=406.4, B=410.7B=410.7, α=0.34\alpha=0.34 and β=0.28\beta=0.28. Extrapolation error can dominate even with a very narrow bootstrap, and the record must say which uncertainty the interval captures and which it does not.

What extrapolation studies show

Gadre and colleagues (2024) built a bank of 104 models from 11 million to 6900 million parameters, trained with varying token counts on three distributions. Laws fitted on experiments costing 300 times less compute predicted validation loss of a 1400 million model trained on 900 000 million tokens (32 times more tokens than its compute-optimal point) and a 6900 million model with 138 000 million tokens; relative error was 0.7 % in both cases. Loss extrapolates well; downstream task accuracy is more fragile. For mean error on 17 tasks of the 6900 million model they obtained 0.05 % relative error, but removing the 1400 million model from the fit raised it to 10.64 %. Their conclusion is that predicting capabilities requires more fitting compute than predicting loss, a direct lesson for capability prediction.

Kaplan and colleagues (2020) fit L(N)∝N−0.076L(N)\propto N^{-0.076}, L(D)∝D−0.095L(D)\propto D^{-0.095} and frontier L∝Cmin⁡−0.050L\propto C_{\min}^{-0.050}, inferring optimal size grows as C0.73C^{0.73}. Chinchilla found exponents near 0.50.5 for size and tokens; part of the difference comes from not matching the rate schedule to each run’s duration and counting parameters without embeddings. None of these numbers serves as an interval for our family, with another architecture, source and six orders of magnitude fewer parameters; the method does transfer.

Choose the validation run

The held-out run must fit in the total budget, not just its own: development sweeps, replicates, evaluation, failure margin and validation itself. The 105 p14-l05 training runs cost 392 GPU seconds; a run at 8⋅10128\cdot10^{12} FLOPs with three parallel seeds costs about 50 seconds on the same RTX 4060. In a real project the proportion is the same and seconds become nights: the validation model is the study’s most expensive and is trained only once.

Configuration is chosen by a registered rule, not by eye. We use approach 2’s allocation law, N∗(C)∝C0.397N_\ast(C)\propto C^{0.397}, yielding N∗(8⋅1012)≈72 756N_\ast(8\cdot10^{12})\approx72\,756; the nearest valid width of p14-l05’s perceptron is 247, with N=72 897N=72\,897 parameters. Tokens follow the same budget rule as development, D=⌊C/(6N⋅2048)⌋⋅2048=18 288 640D=\lfloor C/(6N\cdot2048)\rfloor\cdot2048=18\,288\,640, or 8930 steps and 251 tokens per parameter. Never turn a continuous minimum into an architecture that does not exist: calculate the prediction at the (N,D)(N,D) to be trained.

There are two related but distinct questions. One validates the loss of that fixed configuration; another asks whether it is optimal for the budget. The second would require neighboring NN values at equal compute, a full isoFLOP profile at 8⋅10128\cdot10^{12}. Since we train only one configuration, the record limits the claim to its loss. Data availability is another scope condition: p14-l05’s source generates fresh examples every step, with no repetition; with a finite corpus, processed and unique tokens differ and epochs must be recorded.

Training must use the same pipeline. Freeze data, batching, initialization, architecture, optimizer, precision, evaluation and schedule rule. Some quantities change with horizon under a preregistered rule: cosine matches 8930 steps under the schedule rule, and rate follows η(C)=0.04 (C/5⋅1010)−1/3\eta(C)=0.04\,(C/5\cdot10^{10})^{-1/3}, giving 0.00737. Applying a registered rule differs from selecting a value after seeing loss, although beyond pilot range the rate rule is itself an extrapolation and a risk the record must name.

From uncertain parameters to a prediction

If bootstrap replicate bb of the parametric fit contains (Eb,Ab,Bb,αb,βb)(E_b,A_b,B_b,\alpha_b,\beta_b), natural propagation evaluates every replicate at the same pair (N,D)(N,D):

μb(N,D)=Eb+AbN−αb+BbD−βb.\mu_b(N,D)=E_b+A_bN^{-\alpha_b}+B_bD^{-\beta_b}.

Quantiles of {μb}\{\mu_b\} describe uncertainty of the fitted surface under that resampling and model: the mean band. They are not an interval for a new run’s result, which also varies with initialization, data order and optimizer noise. That requires an explicit model of future error, Yb=μb+ϵbY_b=\mu_b+\epsilon_b, with ϵb\epsilon_b drawn from a justified distribution; if residuals are modeled logarithmically, the coherent combination is Yb=μbeϵbY_b=\mu_be^{\epsilon_b}, not adding a log residual to loss. Each replicate reapplies the full rule, including start selection and rejecting fits on a bound.

The aggregator changes the question. We register the mean of three seeds, so future noise is that of a three-seed mean: using development seed standard deviation 0.00162 nats, its standard deviation is 0.00162/3≈0.000940.00162/\sqrt3\approx0.00094. Predicting a three-seed mean then training one, or training three and publishing the best, no longer answers the registered prediction.

The first two approaches need one more step. An N∗(C)N_\ast(C) law alone gives no loss: different surfaces can share a minimum and have very different values. For profiles we use vertex frontier L∗(C)=E′+k (C/1011)−γL_\ast(C)=E'+k\,(C/10^{11})^{-\gamma} plus parabolic penalty c2(ln⁡N−ln⁡N∗(C))2c_2(\ln N-\ln N_\ast(C))^2 with the largest profile’s curvature, negligible here because configuration comes from the law itself. For the envelope we fit the same frontier to the best measured loss at each budget. Each frontier is another fit with its own decisions: the envelope of final losses takes the minimum of noisy values on a discrete grid, biased downward, and three-parameter frontiers with five points have little room to detect wrong form.

Interval width can depend on budget and marginal widths cannot be added as though independent. Propagate samples jointly, state assumed dependence between fit and noise and, if out-of-range dispersion is unknown, register sensitivity analysis. Calibration methods with a separate set do not solve the problem alone either: their coverage guarantee requires exchangeability between calibration and test, doubtful when the test deliberately uses a much larger model.

Preregistration, hash and provenance

The preregistration turns intent into a reviewable commitment, and is the most direct application of preregistration in machine learning. Include code and data versions, full configuration, planned and effective budget, seeds, metric and aggregator, prediction formula, interval procedure, success criterion, failure treatment and hypotheses expected to be confirmed or refuted. Another person should understand what was decided without asking the experimenter.

A SHA-256 hash summarizes document bytes and detects subsequent changes if a reliable copy of its value is preserved. It does not itself prove date, authorship or that no other candidate documents existed. Verifiable precedence requires an independent mechanism: a commit pushed to a public repository, a timestamped deposit or a dated message to third parties, always containing the hash. Calculating it afterward does not turn a retrospective decision into preregistration.

Serialize the document deterministically before hashing: UTF-8, sorted keys and fixed separators. A different space changes bytes and therefore the hash even if logical content is identical. If anything changes before training, issue a new version and retain the old one with the reason. Declare the set of decisions explored: generating many records with different intervals and publishing the one that succeeded is subtle selection that a hash does not prevent.

An interrupted run needs a prior rule. The record says whether to resume from an intact checkpoint or restart from scratch and how many attempts are allowed. An out-of-memory failure is not infinite loss to mix with predictions or an excuse to change architecture and call the test identical. Our cell reserves the attempt file before training: failure is written as “failed,” interruption leaves “started,” and neither is silently retried.

Lab: register, train and evaluate

The first cell loads means of the 35 p14-l05 configurations, with three seeds each, and defines three approaches so all predict loss at the same (N,D)(N,D) configuration. The surface is fitted as in parametric fitting: Huber with δ=10−3\delta=10^{-3} on log residuals, parameterization using logsumexp, 18 starts and rejection if the optimum touches a bound. Before registering anything it performs forward validation: fit the three or four smaller budgets and predict held-out profile vertices.

[ ]Development data and forward validationLocal GPU
import math, json, hashlib
import numpy as np
from scipy.optimize import minimize
from scipy.special import logsumexp

E_SOURCE = 2.2497  # entropía de la fuente de p14-l05 (nats): la pérdida mínima alcanzable
# presupuesto nominal, anchura, N, tokens procesados y pérdida final de las semillas 11, 22 y 33
RUNS = [
    (5e+10, 33, 2705, 3080192, 2.484607, 2.482718, 2.487667),
    (5e+10, 44, 4080, 2041856, 2.468823, 2.469244, 2.467968),
    (5e+10, 58, 6180, 1347584, 2.458795, 2.460228, 2.459753),
    (5e+10, 74, 9060, 919552, 2.454265, 2.459714, 2.457081),
    (5e+10, 95, 13617, 610304, 2.461409, 2.460647, 2.460106),
    (5e+10, 120, 20192, 411648, 2.464654, 2.466609, 2.469294),
    (5e+10, 152, 30432, 272384, 2.481267, 2.478034, 2.483001),
    (1e+11, 43, 3945, 4222976, 2.456659, 2.458457, 2.453890),
    (1e+11, 56, 5856, 2844672, 2.446812, 2.447133, 2.446303),
    (1e+11, 72, 8672, 1921024, 2.437131, 2.437011, 2.440328),
    (1e+11, 92, 12912, 1290240, 2.437362, 2.437515, 2.434320),
    (1e+11, 117, 19337, 860160, 2.437360, 2.438918, 2.439166),
    (1e+11, 147, 28697, 579584, 2.446720, 2.447407, 2.447551),
    (1e+11, 184, 42720, 389120, 2.455640, 2.460847, 2.453273),
    (2e+11, 54, 5540, 6014976, 2.433198, 2.434385, 2.435698),
    (2e+11, 70, 8292, 4018176, 2.423368, 2.423545, 2.425163),
    (2e+11, 89, 12225, 2725888, 2.416321, 2.417786, 2.417882),
    (2e+11, 113, 18225, 1828864, 2.418169, 2.413412, 2.419422),
    (2e+11, 143, 27345, 1218560, 2.420120, 2.418735, 2.418547),
    (2e+11, 179, 40665, 819200, 2.428605, 2.424587, 2.426109),
    (2e+11, 223, 60465, 550912, 2.439235, 2.437978, 2.436865),
    (4e+11, 67, 7737, 8615936, 2.412279, 2.412019, 2.414325),
    (4e+11, 86, 11556, 5767168, 2.403570, 2.404769, 2.403853),
    (4e+11, 110, 17412, 3827712, 2.398533, 2.398028, 2.399726),
    (4e+11, 138, 25700, 2592768, 2.398507, 2.400633, 2.397146),
    (4e+11, 174, 38660, 1724416, 2.402181, 2.403785, 2.401828),
    (4e+11, 217, 57537, 1157120, 2.410624, 2.409853, 2.410731),
    (4e+11, 270, 85892, 774144, 2.419005, 2.420764, 2.418913),
    (8e+11, 83, 10905, 12226560, 2.393485, 2.393264, 2.392241),
    (8e+11, 106, 16356, 8151040, 2.386983, 2.386122, 2.385728),
    (8e+11, 134, 24420, 5459968, 2.383963, 2.382267, 2.382816),
    (8e+11, 169, 36705, 3631104, 2.386253, 2.383369, 2.384857),
    (8e+11, 211, 54681, 2437120, 2.388089, 2.386395, 2.388216),
    (8e+11, 262, 81252, 1640448, 2.393999, 2.396102, 2.397552),
    (8e+11, 325, 121257, 1097728, 2.403428, 2.404567, 2.402580),
]
C = np.array([r[0] for r in RUNS]); N = np.array([r[2] for r in RUNS], float)
D = np.array([r[3] for r in RUNS], float); LOSS = np.array([r[4:] for r in RUNS])
BUDGETS = sorted(set(C.tolist()))
GAMMAS = np.linspace(0.01, 1.5, 1491)

def parabola(n, l):
    """Vértice de la parábola en ln N: (N*, L*, curvatura)."""
    x = np.log(n); z = x - x.mean()
    c2, c1, c0 = np.polyfit(z, l, 2)
    if c2 <= 0:
        raise ValueError("perfil sin mínimo")
    return math.exp(x.mean() - c1/(2*c2)), c0 - c1**2/(4*c2), c2

def frontier(cs, ls):
    """L*(C) = E + k (C/1e11)^-g por mínimos cuadrados: lineal en (E, k) para cada g de la rejilla."""
    ls = np.asarray(ls)
    X = (np.asarray(cs)/1e11)[None, :] ** -GAMMAS[:, None]          # (g, presupuestos)
    xm, ym = X.mean(1, keepdims=True), ls.mean()
    k = ((X - xm)*(ls - ym)).sum(1)/((X - xm)**2).sum(1)
    E = ym - k*xm[:, 0]
    sse = ((E[:, None] + k[:, None]*X - ls)**2).sum(1)
    i = int(np.argmin(sse))
    return lambda c: E[i] + k[i]*(c/1e11)**-GAMMAS[i]

def surface(budgets, lm, starts):
    """Huber (delta 1e-3) sobre residuos logarítmicos, como en p14-l06; N en 1e4 y D en 1e6."""
    m = np.isin(C, budgets); x, y, lo = np.log(N[m]/1e4), np.log(D[m]/1e6), np.log(lm[m])
    def objective(t):
        e, a, b, al, be = t
        T = np.stack([np.full_like(x, e), a - al*x, b - be*y], 1)
        p = logsumexp(T, 1); w = np.exp(T - p[:, None]); r = p - lo
        h = np.where(np.abs(r) <= 1e-3, .5*r*r, 1e-3*(np.abs(r) - 5e-4))
        J = np.stack([w[:, 0], w[:, 1], w[:, 2], -x*w[:, 1], -y*w[:, 2]], 1)
        return h.sum(), J.T @ np.clip(r, -1e-3, 1e-3)
    bounds = [(-3, 3), (-12, 5), (-12, 5), (.02, 2), (.02, 2)]
    fits = [minimize(objective, s, jac=True, method="L-BFGS-B", bounds=bounds,
                     options={"maxiter": 5000, "ftol": 1e-15, "gtol": 1e-12}) for s in starts]
    best = min(fits, key=lambda f: f.fun)
    edge = any(min(abs(v - lo_), abs(v - hi_)) < 1e-6 for v, (lo_, hi_) in zip(best.x, bounds))
    if not best.success or edge:
        raise ValueError("superficie no identificada")
    return best.x

def predict_all(lm, budgets, n, d, c, starts):
    """Pérdida predicha por los tres enfoques en la misma configuración (n, d) de presupuesto c."""
    budgets = sorted(budgets)
    P = np.array([parabola(N[C == b], lm[C == b]) for b in budgets])
    a, b0 = np.polyfit(np.log(budgets), np.log(P[:, 0]), 1)
    n_star = math.exp(b0)*c**a
    perfiles = frontier(budgets, P[:, 1])(c) + P[-1, 2]*math.log(n/n_star)**2
    envolvente = frontier(budgets, [lm[C == b].min() for b in budgets])(c)
    e, la, lb, al, be = surface(budgets, lm, starts)
    parametrico = math.exp(e) + math.exp(la)*(n/1e4)**-al + math.exp(lb)*(d/1e6)**-be
    return {"envolvente": envolvente, "perfiles": perfiles, "parametrico": parametrico,
            "a": a, "n_star": n_star, "theta": [e, la, lb, al, be]}

LM = LOSS.mean(1)
STARTS = [[e, a, b, al, be] for e in (.6, .8) for a, b in ((-4, -4), (-2, -2), (0, 0))
          for al, be in ((.2, .2), (.5, .5), (1., 1.))]   # 18 inicios
print("Validación hacia adelante en escala (objetivo: vértice del perfil reservado; error = predicho - observado)")
for k in (3, 4):
    for target in BUDGETS[k:]:
        n_v, l_v, _ = parabola(N[C == target], LM[C == target])
        p = predict_all(LM, BUDGETS[:k], n_v, target/(6*n_v), target, STARTS)
        errs = "  ".join(f"{m} {p[m] - l_v:+.4f}" for m in ("envolvente", "perfiles", "parametrico"))
        print(f"  ajuste con {k} presupuestos -> C={target:.0e} (x{target/BUDGETS[k-1]:.0f})  "
              f"observado {l_v:.4f}  error {errs}  E ajustado {math.exp(p['theta'][0]):.4f}")
full = predict_all(LM, BUDGETS, 1e4, 1e6, 1e11, STARTS)
E, A, B = np.exp(full["theta"][:3]); alpha, beta = full["theta"][3:]
print(f"Superficie con los 35 puntos: E={E:.4f} A={A:.4f} B={B:.4f} alfa={alpha:.3f} beta={beta:.3f}")
print(f"Entropía de la fuente {E_SOURCE}; exponente de asignación a={full['a']:.3f}")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Forward validation already reveals almost everything to come. With three budgets, the surface overestimates the 8⋅10118\cdot10^{11} vertex by 0.0057 nats and profiles underestimate it by 0.0073; with four, errors at twice the distance drop to +0.0030+0.0030 and −0.0020-0.0020. More revealing is surface parameter EE: 2.3199 with three budgets, 2.3090 with four and 2.2988 with all five. Every time data are added, estimated irreducible loss falls, and with five it still exceeds source entropy, 2.2497 nats, the true floor. A parametric form whose EE drifts with fitting range absorbs into EE curvature it cannot represent, predicting that it extrapolates overly high losses. We record that hypothesis before training.

The second cell calculates predictions with 200 bootstrap replicates, resampling seeds within each configuration as in p14-l05, adds noise of a three-seed mean and writes the record. If the file already exists it does not overwrite it: it recalculates everything and requires a byte-for-byte match except creation date.

[ ]Hashed preregistered predictionLocal GPU
import datetime as dt
from pathlib import Path

def repo_root():
    for p in [Path.cwd(), *Path.cwd().parents]:
        if (p / "src/content/lessons/p14/l05-perfiles-isoflop.mdx").exists():
            return p
    raise RuntimeError("No se encuentra el repositorio con la lección p14-l05")

def pipeline_source():
    text = (repo_root() / "src/content/lessons/p14/l05-perfiles-isoflop.mdx").read_text(encoding="utf-8")
    marker = '```python run runtime=local title="Fuente, modelo y entrenamiento bajo presupuesto"'
    return text.split(marker, 1)[1].split("```", 1)[0]

def canonical(value):
    return json.dumps(value, sort_keys=True, ensure_ascii=False, separators=(",", ":"),
                      allow_nan=False).encode("utf-8")

# Configuración reservada: diez veces el mayor presupuesto, tamaño según la ley de asignación del enfoque 2
C_VAL = 10*max(BUDGETS)
n_params = lambda w: w*w + 48*w + 32            # la misma cuenta que n_params de p14-l05
n_star = predict_all(LM, BUDGETS, 1e4, 1e6, C_VAL, STARTS)["n_star"]
width = min(range(4, 600), key=lambda w: abs(math.log(n_params(w)/n_star)))
n_val = n_params(width); tokens = int(C_VAL // (6*n_val)) // 2048 * 2048
lr = round(0.04*(C_VAL/5e10)**(-1/3), 5)         # regla de tasa registrada en p14-l05

point = predict_all(LM, BUDGETS, n_val, tokens, C_VAL, STARTS)
rng = np.random.default_rng(2026)
REPS, METHODS = 200, ("envolvente", "perfiles", "parametrico")
boot = {m: [] for m in METHODS}
invalid = 0
for _ in range(REPS):
    draw = rng.integers(0, 3, size=LOSS.shape)            # semillas con reposición dentro de cada celda
    lm = np.take_along_axis(LOSS, draw, 1).mean(1)
    try:   # primero desde el ajuste completo; si no converge, con todos los inicios
        p = predict_all(lm, BUDGETS, n_val, tokens, C_VAL, [point["theta"]])
    except ValueError:
        try:
            p = predict_all(lm, BUDGETS, n_val, tokens, C_VAL, STARTS)
        except ValueError:
            invalid += 1
            continue
    for m in METHODS:
        boot[m].append(p[m])
seed_sd = float(np.sqrt((LOSS.std(1, ddof=1)**2).mean()))  # dispersión entre semillas en desarrollo
predictions = {}
for m in METHODS:
    mu = np.array(boot[m]); future = mu + rng.normal(0, seed_sd/math.sqrt(3), len(mu))
    predictions[m] = {"punto": round(point[m], 5),
                      "media_5_95": np.round(np.quantile(mu, [.05, .95]), 5).tolist(),
                      "predictivo_5_95": np.round(np.quantile(future, [.05, .95]), 5).tolist()}
record = {
    "pregunta": "pérdida media de tres semillas en una ejecución con diez veces el mayor presupuesto",
    "configuracion": {"presupuesto_nominal": C_VAL, "anchura": width, "N": n_val, "tokens": tokens,
                      "flops_6ND": 6*n_val*tokens, "lr": lr, "lote": 2048, "semillas": [11, 22, 33]},
    "datos_desarrollo_sha256": hashlib.sha256(canonical(RUNS)).hexdigest(),
    "pipeline_sha256": hashlib.sha256(pipeline_source().encode("utf-8")).hexdigest(),
    "predicciones": predictions,
    "incertidumbre": f"bootstrap de semillas dentro de cada celda ({REPS} réplicas, semilla 2026) "
                     f"con {invalid} réplicas sin ajuste válido, más ruido gaussiano de la media de tres semillas, sd {seed_sd:.5f}",
    "criterio_exito": "|Y - punto| <= 0.005 nats, con Y la media de las tres semillas",
    "criterio_cobertura": "Y dentro de predictivo_5_95",
    "hipotesis": ["la superficie paramétrica sobrestima Y: su E supera la entropía de la fuente "
                  "y su error fue positivo en la validación hacia adelante",
                  "los intervalos infracubren: solo recogen el ruido de semillas, no el error de forma"],
    "intentos": "uno; si falla o se interrumpe, el resultado queda sin veredicto",
}
folder = Path("resultados/p14-l07"); folder.mkdir(parents=True, exist_ok=True)
REGISTRO = folder / "registro.json"
if REGISTRO.exists():   # nunca se reescribe: se recalcula y se exige que coincida
    stored = json.loads(REGISTRO.read_bytes())
    created = stored.pop("creado_utc")
    if canonical(stored) != canonical(json.loads(canonical(record))):
        raise RuntimeError("El registro guardado no coincide con el recálculo: no se continúa")
    print("Registro existente verificado, creado el", created)
else:
    record["creado_utc"] = dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds")
    with REGISTRO.open("xb") as f:
        f.write(canonical(record))
    print("Registro nuevo creado")
DIGEST = hashlib.sha256(REGISTRO.read_bytes()).hexdigest()
cfg = record["configuracion"]
print(f"Configuración: anchura {width}, N={n_val}, D={tokens}, 6ND={cfg['flops_6ND']:.3e}, "
      f"tasa {lr}, {tokens//2048} pasos")
for m in METHODS:
    p = predictions[m]
    print(f"  {m:12s} punto {p['punto']:.4f}  media 5-95 {p['media_5_95']}  predictivo 5-95 {p['predictivo_5_95']}")
print("SHA-256 del registro:", DIGEST)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The record was written October 27, 2026 at 23:32:04 UTC with hash a93f2fc9ba6f7323566e588ef71011663e8ce1d8c9909c8a0504a1ea9fe53d48. The three point predictions are 2.3374 (envelope), 2.3412 (profiles) and 2.3506 (surface), with 90 % predictive intervals [2.3313,2.3449][2.3313,2.3449], [2.3370,2.3445][2.3370,2.3445] and [2.3488,2.3520][2.3488,2.3520]. The surface interval does not overlap the others, so the experiment can discriminate. Success means absolute error at most 0.005 nats. This is not a comfortable number: predicted improvement over the best development point is 0.032 to 0.046 nats, so 0.005 demands predicting that improvement to about one eighth, and equals about five standard deviations of the three-seed mean.

In this lab precedence relies on program order and timestamps of the files themselves, which someone with disk access could falsify. If a third party must verify it, commit registro.json and push it to a repository with public history before executing the next cell.

The third cell trains the held-out run with p14-l05 code after checking its hash matches the registered one. It reserves the attempt file before starting, compares measured NN and tokens with those registered and applies both rules. If the result already exists, it only reads it.

[ ]Held-out run and verdictLocal GPU
record = json.loads(REGISTRO.read_bytes())
cfg = record["configuracion"]
RESULT = folder / "validacion.json"
if not RESULT.exists():
    # Solo se entrena si el código actual es exactamente el pipeline registrado.
    source = pipeline_source()
    if hashlib.sha256(source.encode("utf-8")).hexdigest() != record["pipeline_sha256"]:
        raise RuntimeError("El pipeline de p14-l05 ha cambiado desde el registro: no se entrena")
    attempt = {"registro_sha256": DIGEST, "estado": "iniciado",
               "inicio_utc": dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds")}
    with RESULT.open("xb") as f:          # el intento queda reservado antes de entrenar
        f.write(canonical(attempt))
    try:
        ns = {}
        exec(compile(source, "pipeline-p14-l05", "exec"), ns)
        run = ns["train_config"](cfg["anchura"], cfg["presupuesto_nominal"], list(cfg["semillas"]),
                                 cfg["lr"], cfg["lote"])
        if run["n"] != cfg["N"] or run["tokens"] != cfg["tokens"]:
            raise RuntimeError("La ejecución no coincide con la configuración registrada")
        attempt.update(estado="terminado", perdidas=run["losses"], segundos=run["secs"],
                       fin_utc=dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds"))
    except Exception as exc:
        attempt.update(estado="fallido", error=f"{type(exc).__name__}: {exc}")
        raise
    finally:
        RESULT.write_bytes(canonical(attempt))
result = json.loads(RESULT.read_bytes())
if result["registro_sha256"] != DIGEST:
    raise RuntimeError("El resultado guardado corresponde a otro registro")
if result["estado"] != "terminado":
    raise RuntimeError(f"Intento en estado {result['estado']}: sin veredicto y sin reintento")
Y = float(np.mean(result["perdidas"]))
print(f"Registro creado {record['creado_utc']}; entrenamiento iniciado {result['inicio_utc']}, "
      f"terminado {result['fin_utc']} ({result['segundos']} s)")
print("Pérdidas por semilla:", np.round(result["perdidas"], 5).tolist(), f"-> Y = {Y:.5f}")
for m, p in record["predicciones"].items():
    lo, hi = p["predictivo_5_95"]
    print(f"  {m:12s} predicho {p['punto']:.4f}  error (predicho - observado) {p['punto'] - Y:+.4f}  "
          f"éxito {abs(Y - p['punto']) <= 0.005}  dentro del intervalo {lo <= Y <= hi}")
print(f"Mejora observada sobre el mejor punto de desarrollo: {LM.min() - Y:.4f} nats")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The attempt was reserved 49 s after registration and the training loop took 51 s. The three seeds yielded 2.33573, 2.33633 and 2.33637, with mean Y=2.33614Y=2.33614: an improvement of 0.0469 nats over the best development point. The registered-rule verdict is:

  • Envelope: predicted 0.0012 nats too high, within tolerance and its interval. Success.
  • Profiles: predicted 0.00504 too high, outside tolerance by 0.00004 nats and outside its interval. Failure.
  • Parametric surface: predicted 0.0144 too high, almost three times tolerance, and the observation lies well below its interval. Failure.

Throughout the lesson error is predicted minus observed, Y^−Y\hat Y-Y: positive means the law was pessimistic.

Both registered hypotheses are confirmed. The surface overestimated loss: it predicted 69 % of the improvement that occurred, versus 89 % for profiles and 97 % for envelope. Two of the three 90 % intervals do not contain the observation because they capture only seed noise. None of this says the envelope is generally the best method: this is one point, all three approaches share data and their ordering may change at another scale.

Evaluate without moving the goalposts

Profile error tests discipline. At 0.00004 nats from the threshold it is tempting to round to three decimals, change tolerance to 0.006 or discard the farthest seed; any of those decisions made now turns registration into decoration. The verdict is “failure.” The report can and should add that the margin is tiny relative to mean noise, 0.000940.00094, and the practical difference from success is nil; that qualification is analysis, not a verdict correction.

The error formula is also fixed beforehand. With a relative criterion, observed loss 2.55 against prediction 2.40 gives 0.15/2.55≈5.88 %0.15/2.55\approx5.88\,\% if dividing by observation and 0.15/2.40=6.25 %0.15/2.40=6.25\,\% if dividing by prediction. Both fail with tolerance 5 %, but at 6 % the denominator decides the verdict. For losses near their floor relative error is also uninformative: 5 % of 2.34 is 0.117 nats, more than twice the entire improvement we sought to predict. Therefore our rule is absolute and calibrated to predicted improvement.

An observation outside an interval does not itself identify a cause. For a well-calibrated 90 % interval, an observation falls outside with probability 0.1 by chance; if all three intervals were calibrated and independent, at least two failures would have probability 0.028. But they are not independent because they share development data, and the most likely explanation for excess failures is what the theorem anticipated: intervals contain only variance. Conversely, an observation inside an enormous interval proves nothing; always report point error and width.

Also allow an inconclusive state. A run with incomplete evaluation, tokens outside tolerance or nonfinite loss counts as neither success nor failure. The report distinguishes “not run,” “inconclusive” when a protocol condition prevents applying the criterion, and “prediction failed” when the protocol was followed and the result does not satisfy the rule. Comparing methods requires evaluating all on the same run, metric and training time, and the record says how ties are resolved and what happens if a method is unidentified.

What to do when prediction fails

Start with a mechanical audit: code and data versions, processed tokens, seeds, finite losses, evaluation mode, precision, schedule and parameter count. Here the cell already checked pipeline hash, N=72 897N=72\,897 and D=18 288 640D=18\,288\,640. A units discrepancy, such as passing NN in thousands to coefficients fitted in tens of thousands, can cause a failure unrelated to the law.

Then formulate competing hypotheses and an experiment distinguishing them, without rewriting the result. For the surface there are at least three. First, the additive form E+AN−α+BD−βE+AN^{-\alpha}+BD^{-\beta} fails to capture this family’s curvature and compensates with an overly high EE; test by fixing EE to source entropy and checking whether development residuals worsen. Second, the rate rule extrapolated to 0.00737 favors this run more than development runs; a short rate profile at 8⋅10128\cdot10^{12} would distinguish this. Third, Huber weighting with δ=10−3\delta=10^{-3} treats as outliers points most informative about curvature. One held-out point cannot confidently separate these explanations, and presenting the first plausible one as proven would be another form of overfitting.

You can now refit the surface including the held-out run, but that new curve is exploratory relative to an already seen observation. To evaluate it, register another prediction for another run not involved in design, for example at 8⋅10138\cdot10^{13} FLOPs, costing about ten GPU minutes. This is the discipline of falsifiable hypotheses: a claim is worth the test that could have overturned it. Also retain consumed budget when the result is negative: knowing actual uncertainty exceeds the bootstrap prevents spending much more based on a precise-looking band.

Exercises

NumericA point prediction
With parametric form E = 1.8, A = 400, α = 0.34, B = 410, β = 0.28 (original units: parameters and tokens), calculate L = E + A/N^α + B/D^β for N = 10^8 and D = 2×10^9.
NumericHow much the band widens
Development budgets are 5×10^10×2^u with u = 0, 1, 2, 3, 4 and a line is fitted in u by least squares with homoscedastic errors. How many times larger is prediction standard deviation at held-out budget 8×10^12 than at range center (u = 2)?
ProofVariance of a linear prediction
Prove: Model y_i = θ₀ + θ₁ x_i + ε_i with uncorrelated mean-zero errors of variance σ², fixed x_i not all equal, S_xx = Σ(x_i − x̄)², and least-squares prediction ŷ(x₀) = θ̂₀ + θ̂₁ x₀. Prove Var ŷ(x₀) = σ²(1/n + (x₀ − x̄)²/S_xx).
0
Write the prediction using centered parameterization.

Step 1 of 4. Which prediction form simplifies the calculation?

QuizA loss outside the interval
The held-out run produces loss outside the registered 90 % predictive interval. What conclusion does this one observation justify?
QuizFailing by four hundred-thousandths
Profiles predicted 2.34118 and observed mean was 2.33614; the registered rule requires absolute error at most 0.005 nats. What should the report say?
NumericBad luck?
If three 90 % predictive intervals were well calibrated and independent, what would be the probability that at least two of the three do not contain the observation?
QuizWhat a hash establishes
A SHA-256 is published with the prediction document. What does the hash alone provide?
CodePropagate a sample of fits
Implement predict_with_uncertainty(fits_bootstrap, N, D). fits_bootstrap is a matrix of rows (E, A, B, α, β), with finite positive values; N and D are positive and use the same units as A and B. Evaluate the surface for each row and return the median and a pair with the 5th and 95th percentiles. Reject incorrect shapes, empty matrices or nonpositive or nonfinite values with ValueError. The interval is for the fitted mean, not predictive of a future run.
import numpy as np

def predict_with_uncertainty(fits_bootstrap, N, D):
  pass
Shift+Enter to run
QuizComparing approaches
You only have a law of optimal N versus compute for each of the first two approaches. Can you compare their loss-prediction error on a held-out model?
Key idea

A preregistered extrapolation fixes configuration, pipeline, prediction, interval and procedure, and verdict rule before training, then applies that rule without moving it. Bootstrap intervals capture only variance, which grows with squared distance from data center; shape bias grows likewise and appears in no resampling. In our test at ten times the largest budget, the envelope succeeded, profiles failed by 0.00004 nats and the parametric surface overestimated loss by three times the tolerance, as anticipated by its EE above source entropy. A hash establishes what was predicted; when it was predicted requires external evidence.