The question
You have fitted a data-scaling exponent on small training sets. The decision is whether to quote it: how much is an exponent measured over 1.5 decades of training-set size worth for predicting the loss one more step out? This study makes that concrete on Fashion-MNIST with one fixed small CNN (23,946 parameters). It fits to the held-out cross-entropy at six training-set sizes, , freezes the law, and then trains once on the full fit pool of 59,992 images and scores the official test set once. The sealed point is the only thing in the study that the law could not see.
The four research questions
- RQ1. What is the exponent over N = 500 to 16,000? The registered prior was 0.1 to 0.6.
- RQ2. Is a pure power law, with no irreducible term, adequate over that range? The registered bar was a log-log R² of at least 0.98.
- RQ3. Does the law predict the full-pool loss within 20 percent?
- RQ4. If it misses, is the measured loss above the law (a saturating curve makes a pure law optimistic)?
The study is typed estimate · image ·
ml-research, with two registered tracks and no keeps: primary
measures one cell per training-set size, and exponent holds the one fit.
Seven predictions (P1 to P7) were registered with arithmetic rules before the
evidence they judge.
Takeaways
- The exponent is shallow and the pure law is a poor description. The fit gives with log-log , far under the registered 0.98 (claims C1, C2). The three smallest cells are flat where a power law needs a decline.
- The sealed extrapolation missed, in the opposite direction to the registered bet. The law predicted 0.5066 nats at the full pool; the sealed cell measured 0.3959, a signed relative error of −0.2802. The law was pessimistic, not optimistic (C3, C4).
- The mechanism is not established. One reading, that the smallest cells are compute-limited at a shared 400-step budget, is recorded as a hypothesis, untested (C9). No cell was run to test it.
Two things to hold while reading. The six fit cells are scored on the development lane (official train rows 50,000 to 59,999) while the sealed cell is scored on the official t10k test set, so the extrapolation error cannot be split exactly between the law and the partition (C16). And the evidence block in section 5 gives the claim totals and the referee's verdict exactly as the records hold them.
The method taught
A fitted exponent is a tangent line, not a law
On log-log axes almost any smooth, decreasing curve looks straight over a short enough interval. A fit over 1.5 decades measures the average local slope over that interval. That slope can be pinned precisely and still be the wrong slope to extrapolate with. The question the study asks is not “how well is the line pinned?” but “is the curve still a line out there?”
The law and how it is fitted
The pure law is a power in the training-set size, and taking logs turns the fit into ordinary least squares on the six seed-mean losses:
Each cell is a 3-seed array and the fit uses the seed mean of the development cross-entropy at each of the six sizes. R² is computed in log space. The printed interval for is a percentile bootstrap that resamples seeds within each N. Because subsamples are nested within a seed (the 500 images are part of the 1,000, and so on), that bootstrap is only a descriptive spread, never a calibrated 95% interval.
Why the curve might bend
For a fixed model the data curve is expected to saturate at a model-dependent floor. The saturating alternative is
A floor makes the local slope decay toward zero as N grows, so a straight line fitted on the steep early part predicts a loss that is too low further out: the pure law would be optimistic. That is the bet behind P4 and P6. R² cannot arbitrate: the method card's synthetic checks show a curve whose pure-law extrapolation misses by 20 percent can still score R² above 0.98.
The sealed test and its error
After the fit is frozen, the network is trained once on the whole pool and scored once on the test set. For each seed the study records the signed relative error, and the notary averages it over the three seeds:
A positive means the law was optimistic. P3 asks whether , P4 whether , and P6 whether lies in [0.03, 0.25]. The seed mean of per-seed errors differs slightly from the error of the seed-mean loss (erratum E1 in section 5 records that); the verdicts do not change.
The training protocol the cells share
The network, optimizer and schedule are fixed in lib/protocol.py, outside the
mutable surface, so a cell changes N and nothing else. A cell trains for
optimizer steps, where is the 90 percent of the subsample it trains on. The other 10 percent is an inner validation set used to keep the best checkpoint, which is early stopping. This is the load-bearing design detail for the rest of the page: the 400-step floor means the three smallest cells share one budget, as section 4 shows.
The data story
Fashion-MNIST: 28×28 greyscale images, 10 classes, four IDX files each pinned by sha256
in study.yaml. No pretrained weights are involved. The call is
GO-WITH-CAUTIONS; no BLOCKER is open.
Shape and partitions
| Partition | Rows | Defined by | Used for |
|---|---|---|---|
| train | 50,000 | official train rows 0 to 49,999 | every development cell draws its N-image subsample from here |
| development | 9,992 | official train rows 50,000 to 59,999, minus 8 near-copies | scores the six fit cells |
| test (sealed) | 9,995 | official t10k, minus 5 near-copies | scored once, by the sealed full-pool cell |
The sealed fit pool is train plus development, 59,992 images. Partitions are positions, not a
seed: prepare.py holds no random state, and the seed: 42 in the contract is declared inert.
The gotcha: a tooling false positive on small silhouettes
The first audit used a 64-bit difference hash and flagged 56 percent of held-out images as near-duplicates of training images. None were byte-identical. On 28×28 silhouettes a 64-bit hash collides constantly, so this was a false positive of the tool, not a leak. The fix was an exact pixel-space criterion: nearest fit-pool image by pixel RMS, with copies at 4 grey levels or less removed. That removed 8 development images and 5 test images, and the re-run pixel audit passes with no held-out image within 4 grey levels of any fit-pool image. The dHash result is kept in the card verbatim and is not the criterion of record.
The cautions that carry into the findings
- WARN: the partitions are not one draw. Development rows come from the train file and the sealed rows from t10k. The measured per-image standardized difference is +0.015, with no detectable first-order covariate shift, which is not proof of none, and the data card measured no loss gap. This is the origin of the cross-partition caveat on C16.
- WARN: no group ids. Same-product, different-view twins cannot be audited.
- NOTE: the chance-level check was deferred. It is not mechanizable in index mode and no later step took it up, which is why no negative control exists (section 5).
The experiment journey
Two registered tracks, no frontier and no keeps. A registered track measures: every
run is a pre-registered cell, recorded as measured or crash. There were no
crashes, no discards and no sweeps. The ledger below is generated from the run manifests; the figures
are drawn from the committed per-seed tables and manifests.
Tracks: primary — val_mlogloss (lower is better) · exponent — scaling_exponent (higher is better)
| Exp | Track | Kind | Metric | Status | Description |
|---|---|---|---|---|---|
| E0001 | primary | development | 0.829647333333 | measured | cell N=500; registered cell measured |
| E0002 | primary | development | 0.949174333333 | measured | cell N=1000; registered cell measured |
| E0003 | primary | development | 0.840758666667 | measured | cell N=2000; registered cell measured |
| E0004 | primary | development | 0.756999333333 | measured | cell N=4000; registered cell measured |
| E0005 | primary | development | 0.652339666667 | measured | cell N=8000; registered cell measured |
| E0006 | primary | development | 0.563684 | measured | cell N=16000; registered cell measured |
| E0007 | exponent | development | 0.13036 | measured | fit: the power law over the six cells; registered cell measured |
| E0008 | primary | final_test | 0.395864 | measured | sealed confirmation: full pool N=59,992; registered cell measured |
How the runs were executed, and what that does to the evidence
E0001 to E0006 (the six development cells) ran as detached jobs: the notary committed
the candidate, a host executed it, and the receipt was collected and judged locally. Each manifest says
mode: detached and observed_by_notary: false, so these are attested, not observed.
Of the claims' evidence, only E0005 was re-executed under observation (rep:E0005@20261103T084144Z,
difference 0). E0007 (the fit) and E0008 (the sealed cell) ran in the foreground under the notary, and the fit's
replication rep:E0007@20261103T084735Z re-ran its arithmetic on the pinned cells, not the cells themselves.
Further replication records for E0001 to E0004 and E0006 sit in the run directories, all with difference 0; they were
filed after the claims were locked and no claim cites them.
Phase 1: the six development cells (primary track)
Ascending N was chosen for cheapness and to fail fast on the detached path. The first two cells already broke the script of a power law: N=1000 (E0002) came out worse than N=500 (E0001). The journal recorded it as measured and did not retry. The next section on findings shows that the inversion is present in all three paired seeds.
Phase 2: the fit (exponent track)
E0007 fits the pure law over the six pinned cells, and adjudicated P1, P2 and P5 by the notary's arithmetic, not by prose. The fitted exponent is inside the wide P1 range and below the sharper P5 range.
The scaling picture: six cells, one law, one sealed point
Phase 3: the sealed extrapolation (confirmation evidence, labelled separately)
The sealed cell E0008 is confirmation evidence, not part of the development series. Its dry run trained only 60 steps on development data and spent nothing; the real run trained the full 8437-step budget for three seeds, in the foreground, and read the test set once. The prediction came from the fit frozen at E0007, and the fit table was hash-checked before training began. Section 5 gives the verdicts.
The lab notebook, with one correction to the reader's trust
The cell journal in program.md contains three contemporaneous entries that state the
compute-limited mechanism as fact. The referee required that they not be taken that way: they are readings,
superseded by claim C9's status, hypothesis, untested. This page uses C9's status and not the
notebook's phrasing.
Findings & insights
- claims
17locked inclaims.lock- by strength
- confirmed
5· exploratory12 - by class
- empirical-description
7· mechanism-interpretation2· procedural-verdict3· research-discipline5 - errata
2of17claims tagged ·2erratum record(s) in the lock- locked at
68dc7756e919· klein2.2.0- label
- confirmed
- referee
- PASS-WITH-NOTES —
klein-referee (Claude Code subagent, model: claude-opus-5-5)· independent of the experimenter: yes
The evidence block above is copied from the records. The verdicts below cite claim ids from the lock
(22-cnn-data-scaling#Cn); the sentence of each claim is the one in claims.lock.
Verdicts on the four questions
- RQ1, answered (C1). The pure law fitted to the six seed-mean development cells has exponent 0.1304 and prefactor 2.126. The prior's range was 0.1 to 0.6, so P1 is supported, but the exponent sits below the “most likely 0.2 to 0.4” band and below the sharper P5 range (refuted). The printed bootstrap spread, 0.1181 to 0.1411, is descriptive; a post-hoc per-seed-slope t-interval is 0.1033 to 0.1569.
- RQ2, refuted (C2). Log-log R² is 0.7955 against the registered 0.98. The three smallest cells are flat at 0.8296, 0.9492 and 0.8408 where the law needs a decline.
- RQ3, refuted (C3). Measured 0.3959 (seed sd 0.0090) against predicted 0.5066: a signed relative error of −0.2802, outside the 0.20 bar.
- RQ4, refuted with the opposite sign (C4). The measured loss is below the prediction by 0.1107 nats, so the law was pessimistic. P4 and P6 are refuted.
Of the seven registered predictions, only P1 and P7 were supported. P7, the only sharp METHOD-gate prior that held, was about training dynamics rather than the curve: the full-pool cell's best checkpoint came at step 8050 of 8437 (C5). Erratum E1 notes that −0.2802 is the seed mean of per-seed errors (the registered definition); the signed error of the seed-mean loss is −0.2797. Verdict unchanged.
Surprises, and how much of each is actually known
The small end is flat, and N=1000 is worse than N=500. Local exponent over the three smallest cells is −0.0096 against 0.2127 over the three largest, so the curve steepens with N, contradicting the method card's expectation that it would flatten (C7). N=1000 sits above N=500 on nested, paired subsamples and the inversion is present in all three paired seeds, by +0.1195 on average (C8). Every cell's best checkpoint came at 0.954 or more of its step budget, and the three smallest cells shared one 400-step floor with 113.8, 56.9 and 28.4 epochs (C6).
Mechanism: a hypothesis, untested (C9). The status of C9 as locked: hypothesis, untested. It says the small end may be compute-limited, so that at a shared 400-step budget the loss would track steps more than data. No step-matched or step-extended small cell was run, so this stands untested, and rival readings fit the same evidence: the small-data region that Hestness et al. describe, and non-monotone learning curves of a fixed model. The N=1000 inversion itself is unresolved; checkpoint selection on 50- and 100-image inner sets is visibly optimistic at N=500, but that was not isolated.
Even the friendliest refit over-predicts. A post-hoc, unregistered refit over the three largest cells alone gives exponent 0.2127 and predicts 0.4254, still above the measured 0.3959 (C10). Whether the curve kept steepening past N=16000 is a cross-partition reading only, with a descriptive local exponent of 0.2674 that is confounded with the development-versus-test gap. The held-out over inner-validation loss ratios do not show the test set easier or harder (C11, re-scoped by erratum E2); this stays exploratory.
The printed interval is too narrow (C12). The bootstrap width is 0.0230 exponent units and the per-seed-slope t-interval has width 0.0536, which is 2.33 times wider. The card expected exactly this, and the interval prior held.
What this study did not do
- The cross-partition caveat applies to C3, C4 and the sealed point. The six fit cells are scored on the development lane and the sealed cell on the official test set (C16). A same-partition control was not run.
- No negative control was run — no shuffled-label cell and no check against the chance level ln 10. The record gives no reason. The one positive control, a synthetic harness recovering a planted exponent, covers the fit code only, not training or evaluation. The cell losses sit far below chance, which is a sanity bound, not a control.
- Re-execution is thin. E0001 to E0006 are attested detached runs, and only E0005 was re-executed under observation by the evidence the claims cite. The replication of the fit repeats arithmetic on pinned cells.
- The noise floor was never separately measured. Both tracks are registered, so no claim leans on a keep bar; the per-cell seed spread is the only noise measure, and the contract's
minimum_deltais a resolution, not a measured floor.
Practitioner impact: what to change in a training recipe, and at what cost
No materiality block is registered, so nothing is priced. The change that the evidence motivates is to make the step budget grow with N across the whole fitted range, with no minimum that several cells share, and to check that no best checkpoint sits at the end of its budget (C13); motivation is the measured shape (C6 to C8) and not the untested mechanism. The cells were not matched in compute, so the exponent is a property of this protocol, not of the network alone. Measured on a 4-CPU x86_64 Linux VM with no GPU: the sealed 3-seed array took 1883.8 s of wall time, and wall time is informational only.
Training-recipe advice
This section walks the code that produced the evidence. The surface a candidate may change is one file,
analyze.py, and one line of it: CELL["n_train"]. The training protocol
(lib/protocol.py) and the fit arithmetic (lib/scaling.py) sit outside the mutable surface, so no cell can
quietly change how it trains. The source below is included by reference to the run that executed it, not the file left on disk
(the notary restores analyze.py after every run on a registered track). Each listing opens as a collapsed disclosure.
A development cell: E0006 (N = 16,000)
E0006 is the representative cell. Read the file top to bottom in four moves. (1) Partitions come from the contract
through load_items, which prints the split_fingerprint the notary compares with the one frozen at the DATA gate, so
a cell cannot silently score the wrong rows. (2) draw_subsample takes N images from one permutation seeded by the seed,
which makes subsamples nested within a seed, and holds out 10 percent as an inner validation set. (3) protocol.train keeps the best
inner-validation checkpoint and returns its step. (4) The cell pins tables/cell_<run>_s<seed>.tsv, a name the fit
collects, while the sealed run writes sealed_<run>_s<seed>.tsv, a name no fit can ever pick up.
analyze.py · executed by E0006 (development, track primary) at commit c4b9823e3784 · sha256 4664bb1d923c…
"""Data-scaling cells, the power-law fit, and the sealed extrapolation — THE mutable surface.
A candidate changes ONE thing: ``CELL["n_train"]`` (the training-set size N of a
`primary` development cell). The training protocol is fixed in `lib/protocol.py`
and the fit arithmetic in `lib/scaling.py`, both outside `entrypoint.mutable`.
Tracks (`KLEIN_TRACK`, set by `klein run-one`):
* ``primary`` — development: the seed (`KLEIN_SEED`; `entrypoint.seeds` makes one
cell a 3-seed array) draws N items of the train partition, holds out 10% as an
inner validation set, trains the fixed protocol, and scores the best
inner-validation checkpoint on the development partition (`val_mlogloss`). It
pins ``tables/cell_<run>_s<seed>.tsv`` (run, seed, n_train, val_mlogloss,
best_step) and the per-seed confusion table.
SEALED (`klein run-one --final-test`, ``KLEIN_EVALUATION_KIND=final_test``):
the fit pool is train + development (60,000) and N is all of it; the test
partition is scored once, and the pinned law ``tables/scaling_fit.tsv`` is
compared with this seed's measured loss (`predicted_loss`,
`extrapolation_rel_error`). It pins ``tables/sealed_<run>_s<seed>.tsv`` — NOT a
``cell_*`` name, so a later fit can never pick up a sealed number.
* ``exponent`` — fits ``log L = log a - alpha log N`` over the seed means of every
pinned development cell and prints alpha with its bootstrap interval
(`scaling_exponent`, `fit_r2`), pinning ``tables/scaling_fit.tsv``. The fit is
deterministic, so the seed array prints three identical blocks.
The partitions come from the contract: `kleinlib.data.load_items()` is the
index-table wrapper of `kleinlib.data.load_partition()`, prints the
`split_fingerprint:` the notary checks, and under ``KLEIN_SEALED_DRYRUN=1``
answers a sealed request with the development partition plus ``sealed_dryrun: 1``.
``KLEIN_SMOKE=1`` is a shape check: N = 300, 30 steps, nothing written. It never
reads the sealed partition (a smoke ``final_test`` must also set
``KLEIN_SEALED_DRYRUN=1``).
"""
from __future__ import annotations
import os
import time
from pathlib import Path
import numpy as np
import pandas as pd
from lib import protocol, scaling # the study's fixed machinery, beside this file
from kleinlib.data import load_items, partition_fingerprints
from kleinlib.dl import report_usage, seed_everything
from kleinlib.eval import evaluate_estimate
from kleinlib.eval_multiclass import evaluate_multiclass, multiclass_metrics
from kleinlib.primitives import sha256_file
from kleinlib.torch_device import pick_device
HERE = Path(__file__).resolve().parent
# --- the candidate: the whole per-experiment diff ------------------------------
CELL = {"n_train": 16000}
# -------------------------------------------------------------------------------
SMOKE = os.environ.get("KLEIN_SMOKE") == "1"
DRY_RUN = os.environ.get("KLEIN_SEALED_DRYRUN") == "1"
FINAL = os.environ.get("KLEIN_EVALUATION_KIND") == "final_test"
EXPERIMENT_ID = os.environ.get("KLEIN_EXPERIMENT_ID") or ("SMOKE" if SMOKE else None)
TRACK = os.environ.get("KLEIN_TRACK") or ("primary" if SMOKE else None)
SEED = int(os.environ.get("KLEIN_SEED", "0"))
LABELS = list(range(protocol.N_CLASSES))
def run_primary(t0: float) -> None:
if SMOKE and FINAL and not DRY_RUN:
raise SystemExit("a smoke run never reads the sealed partition: add KLEIN_SEALED_DRYRUN=1")
sealed = FINAL and not DRY_RUN
fit_law = None
if FINAL:
# Read the pinned law BEFORE training: a missing fit crashes in seconds,
# not after the whole full-data budget.
fit_path = HERE / scaling.FIT_TABLE
if not SMOKE:
pin = scaling.pinning_manifest(HERE, scaling.FIT_TABLE, track="exponent")
if pin is None:
raise SystemExit(f"{scaling.FIT_TABLE} is not pinned by a measured exponent run")
if pin["artifacts"][scaling.FIT_TABLE].get("sha256") != sha256_file(fit_path):
raise SystemExit(f"{scaling.FIT_TABLE} differs from the bytes {pin['experiment']} pinned")
fit_law = scaling.read_fit(fit_path)
fit_ids, eval_ids = load_items(study_dir=HERE) # prints split_fingerprint (+ sealed_dryrun)
n_pool = len(fit_ids)
if SMOKE:
n = protocol.SMOKE_N_TRAIN
elif FINAL:
n = n_pool # the full-data cell: every item of the fit pool
else:
n = int(CELL["n_train"])
if sealed and n != protocol.N_FULL:
raise SystemExit(f"the sealed cell must train on N={protocol.N_FULL}, the fit pool holds {n_pool}")
seed_everything(SEED, deterministic=True)
rng = np.random.default_rng(SEED)
fit_pos, inner_pos = protocol.draw_subsample(n_pool, n, rng)
store = protocol.ItemStore(HERE / "data" / "prepared")
x_fit, y_fit = store.load([fit_ids[i] for i in fit_pos])
x_inner, y_inner = store.load([fit_ids[i] for i in inner_pos])
x_eval, y_eval = store.load(eval_ids)
steps = protocol.SMOKE_STEPS if SMOKE else (protocol.DRYRUN_STEPS if DRY_RUN else protocol.steps_for(n))
every = protocol.SMOKE_EVAL_EVERY if SMOKE else protocol.eval_every(steps)
model, info = protocol.train(x_fit, y_fit, x_inner, y_inner, steps=steps, every=every, rng=rng, device=pick_device())
proba = protocol.predict_proba(model, x_eval, next(model.parameters()).device)
report_usage(steps=info["steps"])
extra: dict[str, float | int] = {
"n_train": n,
"n_fit": len(fit_pos),
"n_inner": len(inner_pos),
"steps": info["steps"],
"eval_every": every,
"best_step": info["best_step"],
"best_inner_loss": round(info["best_inner_loss"], 6),
}
if FINAL:
# The measured loss of THIS seed (the same number the block prints).
measured = multiclass_metrics(y_eval, proba, labels=LABELS)[0]["val_mlogloss"]
a, alpha = fit_law
law = scaling.extrapolation(a, alpha, n, measured)
# Per seed: predicted = a * N**(-alpha) at THIS run's N (60,000 on the
# sealed run; the 50,000-item train partition on a dry run, so the
# rehearsal compares like with like), and
# extrapolation_rel_error = (measured - predicted) / measured. The notary
# averages every printed key over the seed array, so the run's
# `extrapolation_rel_error` is the SEED MEAN OF THE PER-SEED RELATIVE
# ERRORS — which differs from (mean measured - predicted) / mean measured
# only at second order in the seed spread (Jensen); P3 and P4 read the
# former. Both are recomputable from the pinned sealed tables.
extra.update({"fit_a": a, "fit_alpha": alpha, **law})
# Under the seed array the evaluator pins tables/confusion_<run>_s<seed>.tsv itself.
writes = not (SMOKE or DRY_RUN) # the dry run must leave the tree as it found it
value = evaluate_multiclass(
y_eval, proba, labels=LABELS, exp_id=EXPERIMENT_ID, metric_name="val_mlogloss", t0=t0,
fit_seconds=info["fit_seconds"], train_n=len(fit_pos), extra=extra,
study_dir=HERE if writes else None,
)
if writes:
row = {"run": EXPERIMENT_ID, "seed": SEED, "n_train": n, "val_mlogloss": f"{value:.6f}", "best_step": info["best_step"]}
if FINAL:
name = f"tables/sealed_{EXPERIMENT_ID}_s{SEED}.tsv"
row.update({k: f"{float(extra[k]):.10g}" for k in ("fit_a", "fit_alpha", "predicted_loss", "extrapolation_rel_error")})
else:
name = f"tables/cell_{EXPERIMENT_ID}_s{SEED}.tsv"
(HERE / "tables").mkdir(parents=True, exist_ok=True)
pd.DataFrame([row]).to_csv(HERE / name, sep="\t", index=False, lineterminator="\n")
print(f"artifact: {name}")
def run_exponent(t0: float) -> None:
if FINAL:
raise SystemExit("the exponent track takes no sealed run (its confirmation is a replication)")
table, notes = scaling.collect_cells(HERE, require_pinned=not SMOKE)
for note in notes:
print(f"note: {note}")
per_n, params = scaling.fit_cells(table, n_full=protocol.N_FULL)
# The fit's inputs were measured on the development partition; print its
# fingerprint so the notary can hold the fit to the same rows.
fingerprint = partition_fingerprints(HERE)["development"]
if not SMOKE:
rel = scaling.write_fit(HERE, per_n)
print(f"artifact: {rel}")
evaluate_estimate(
params["alpha"], params["alpha_ci_low"], params["alpha_ci_high"], int(params["n_cell_rows"]),
exp_id=EXPERIMENT_ID, metric_name="scaling_exponent", metric_goal="higher", t0=t0,
extra={
"fit_r2": params["fit_r2"],
"a": params["a"],
"n_sizes": int(params["n_sizes"]),
"predicted_loss_at_full": params["predicted_loss_at_full"],
"ci_clamped": int(params["ci_clamped"]),
},
split_fingerprint=fingerprint,
study_dir=None if SMOKE else HERE,
)
def main() -> None:
if EXPERIMENT_ID is None or TRACK is None:
raise SystemExit("run through `klein run-one` (or KLEIN_SMOKE=1 for a shape check)")
t0 = time.time()
if TRACK == "primary":
run_primary(t0)
elif TRACK == "exponent":
run_exponent(t0)
else:
raise SystemExit(f"unknown track {TRACK!r} (primary | exponent)")
if __name__ == "__main__":
main()
The fit: E0007
The exponent track runs the same file with KLEIN_TRACK=exponent, which calls run_exponent. It collects only cell tables whose
run is a measured primary development run, whose path is pinned in its manifest, and whose bytes still hash to the pin; a table
that fails that is not evidence. The arithmetic lives in lib/scaling.py: OLS on the log-log seed means, R² in log space,
and a within-N bootstrap that the file itself labels descriptive.
analyze.py · executed by E0007 (development, track exponent) at commit 580835ce38d1 · sha256 ccf9f09a349b…
"""Data-scaling cells, the power-law fit, and the sealed extrapolation — THE mutable surface.
A candidate changes ONE thing: ``CELL["n_train"]`` (the training-set size N of a
`primary` development cell). The training protocol is fixed in `lib/protocol.py`
and the fit arithmetic in `lib/scaling.py`, both outside `entrypoint.mutable`.
Tracks (`KLEIN_TRACK`, set by `klein run-one`):
* ``primary`` — development: the seed (`KLEIN_SEED`; `entrypoint.seeds` makes one
cell a 3-seed array) draws N items of the train partition, holds out 10% as an
inner validation set, trains the fixed protocol, and scores the best
inner-validation checkpoint on the development partition (`val_mlogloss`). It
pins ``tables/cell_<run>_s<seed>.tsv`` (run, seed, n_train, val_mlogloss,
best_step) and the per-seed confusion table.
SEALED (`klein run-one --final-test`, ``KLEIN_EVALUATION_KIND=final_test``):
the fit pool is train + development (60,000) and N is all of it; the test
partition is scored once, and the pinned law ``tables/scaling_fit.tsv`` is
compared with this seed's measured loss (`predicted_loss`,
`extrapolation_rel_error`). It pins ``tables/sealed_<run>_s<seed>.tsv`` — NOT a
``cell_*`` name, so a later fit can never pick up a sealed number.
* ``exponent`` — fits ``log L = log a - alpha log N`` over the seed means of every
pinned development cell and prints alpha with its bootstrap interval
(`scaling_exponent`, `fit_r2`), pinning ``tables/scaling_fit.tsv``. The fit is
deterministic, so the seed array prints three identical blocks.
The partitions come from the contract: `kleinlib.data.load_items()` is the
index-table wrapper of `kleinlib.data.load_partition()`, prints the
`split_fingerprint:` the notary checks, and under ``KLEIN_SEALED_DRYRUN=1``
answers a sealed request with the development partition plus ``sealed_dryrun: 1``.
``KLEIN_SMOKE=1`` is a shape check: N = 300, 30 steps, nothing written. It never
reads the sealed partition (a smoke ``final_test`` must also set
``KLEIN_SEALED_DRYRUN=1``).
"""
from __future__ import annotations
import os
import time
from pathlib import Path
import numpy as np
import pandas as pd
from lib import protocol, scaling # the study's fixed machinery, beside this file
from kleinlib.data import load_items, partition_fingerprints
from kleinlib.dl import report_usage, seed_everything
from kleinlib.eval import evaluate_estimate
from kleinlib.eval_multiclass import evaluate_multiclass, multiclass_metrics
from kleinlib.primitives import sha256_file
from kleinlib.torch_device import pick_device
HERE = Path(__file__).resolve().parent
# --- the candidate: the whole per-experiment diff ------------------------------
CELL = {"n_train": 500}
# -------------------------------------------------------------------------------
SMOKE = os.environ.get("KLEIN_SMOKE") == "1"
DRY_RUN = os.environ.get("KLEIN_SEALED_DRYRUN") == "1"
FINAL = os.environ.get("KLEIN_EVALUATION_KIND") == "final_test"
EXPERIMENT_ID = os.environ.get("KLEIN_EXPERIMENT_ID") or ("SMOKE" if SMOKE else None)
TRACK = os.environ.get("KLEIN_TRACK") or ("primary" if SMOKE else None)
SEED = int(os.environ.get("KLEIN_SEED", "0"))
LABELS = list(range(protocol.N_CLASSES))
def run_primary(t0: float) -> None:
if SMOKE and FINAL and not DRY_RUN:
raise SystemExit("a smoke run never reads the sealed partition: add KLEIN_SEALED_DRYRUN=1")
sealed = FINAL and not DRY_RUN
fit_law = None
if FINAL:
# Read the pinned law BEFORE training: a missing fit crashes in seconds,
# not after the whole full-data budget.
fit_path = HERE / scaling.FIT_TABLE
if not SMOKE:
pin = scaling.pinning_manifest(HERE, scaling.FIT_TABLE, track="exponent")
if pin is None:
raise SystemExit(f"{scaling.FIT_TABLE} is not pinned by a measured exponent run")
if pin["artifacts"][scaling.FIT_TABLE].get("sha256") != sha256_file(fit_path):
raise SystemExit(f"{scaling.FIT_TABLE} differs from the bytes {pin['experiment']} pinned")
fit_law = scaling.read_fit(fit_path)
fit_ids, eval_ids = load_items(study_dir=HERE) # prints split_fingerprint (+ sealed_dryrun)
n_pool = len(fit_ids)
if SMOKE:
n = protocol.SMOKE_N_TRAIN
elif FINAL:
n = n_pool # the full-data cell: every item of the fit pool
else:
n = int(CELL["n_train"])
if sealed and n != protocol.N_FULL:
raise SystemExit(f"the sealed cell must train on N={protocol.N_FULL}, the fit pool holds {n_pool}")
seed_everything(SEED, deterministic=True)
rng = np.random.default_rng(SEED)
fit_pos, inner_pos = protocol.draw_subsample(n_pool, n, rng)
store = protocol.ItemStore(HERE / "data" / "prepared")
x_fit, y_fit = store.load([fit_ids[i] for i in fit_pos])
x_inner, y_inner = store.load([fit_ids[i] for i in inner_pos])
x_eval, y_eval = store.load(eval_ids)
steps = protocol.SMOKE_STEPS if SMOKE else (protocol.DRYRUN_STEPS if DRY_RUN else protocol.steps_for(n))
every = protocol.SMOKE_EVAL_EVERY if SMOKE else protocol.eval_every(steps)
model, info = protocol.train(x_fit, y_fit, x_inner, y_inner, steps=steps, every=every, rng=rng, device=pick_device())
proba = protocol.predict_proba(model, x_eval, next(model.parameters()).device)
report_usage(steps=info["steps"])
extra: dict[str, float | int] = {
"n_train": n,
"n_fit": len(fit_pos),
"n_inner": len(inner_pos),
"steps": info["steps"],
"eval_every": every,
"best_step": info["best_step"],
"best_inner_loss": round(info["best_inner_loss"], 6),
}
if FINAL:
# The measured loss of THIS seed (the same number the block prints).
measured = multiclass_metrics(y_eval, proba, labels=LABELS)[0]["val_mlogloss"]
a, alpha = fit_law
law = scaling.extrapolation(a, alpha, n, measured)
# Per seed: predicted = a * N**(-alpha) at THIS run's N (60,000 on the
# sealed run; the 50,000-item train partition on a dry run, so the
# rehearsal compares like with like), and
# extrapolation_rel_error = (measured - predicted) / measured. The notary
# averages every printed key over the seed array, so the run's
# `extrapolation_rel_error` is the SEED MEAN OF THE PER-SEED RELATIVE
# ERRORS — which differs from (mean measured - predicted) / mean measured
# only at second order in the seed spread (Jensen); P3 and P4 read the
# former. Both are recomputable from the pinned sealed tables.
extra.update({"fit_a": a, "fit_alpha": alpha, **law})
# Under the seed array the evaluator pins tables/confusion_<run>_s<seed>.tsv itself.
writes = not (SMOKE or DRY_RUN) # the dry run must leave the tree as it found it
value = evaluate_multiclass(
y_eval, proba, labels=LABELS, exp_id=EXPERIMENT_ID, metric_name="val_mlogloss", t0=t0,
fit_seconds=info["fit_seconds"], train_n=len(fit_pos), extra=extra,
study_dir=HERE if writes else None,
)
if writes:
row = {"run": EXPERIMENT_ID, "seed": SEED, "n_train": n, "val_mlogloss": f"{value:.6f}", "best_step": info["best_step"]}
if FINAL:
name = f"tables/sealed_{EXPERIMENT_ID}_s{SEED}.tsv"
row.update({k: f"{float(extra[k]):.10g}" for k in ("fit_a", "fit_alpha", "predicted_loss", "extrapolation_rel_error")})
else:
name = f"tables/cell_{EXPERIMENT_ID}_s{SEED}.tsv"
(HERE / "tables").mkdir(parents=True, exist_ok=True)
pd.DataFrame([row]).to_csv(HERE / name, sep="\t", index=False, lineterminator="\n")
print(f"artifact: {name}")
def run_exponent(t0: float) -> None:
if FINAL:
raise SystemExit("the exponent track takes no sealed run (its confirmation is a replication)")
table, notes = scaling.collect_cells(HERE, require_pinned=not SMOKE)
for note in notes:
print(f"note: {note}")
per_n, params = scaling.fit_cells(table, n_full=protocol.N_FULL)
# The fit's inputs were measured on the development partition; print its
# fingerprint so the notary can hold the fit to the same rows.
fingerprint = partition_fingerprints(HERE)["development"]
if not SMOKE:
rel = scaling.write_fit(HERE, per_n)
print(f"artifact: {rel}")
evaluate_estimate(
params["alpha"], params["alpha_ci_low"], params["alpha_ci_high"], int(params["n_cell_rows"]),
exp_id=EXPERIMENT_ID, metric_name="scaling_exponent", metric_goal="higher", t0=t0,
extra={
"fit_r2": params["fit_r2"],
"a": params["a"],
"n_sizes": int(params["n_sizes"]),
"predicted_loss_at_full": params["predicted_loss_at_full"],
"ci_clamped": int(params["ci_clamped"]),
},
split_fingerprint=fingerprint,
study_dir=None if SMOKE else HERE,
)
def main() -> None:
if EXPERIMENT_ID is None or TRACK is None:
raise SystemExit("run through `klein run-one` (or KLEIN_SMOKE=1 for a shape check)")
t0 = time.time()
if TRACK == "primary":
run_primary(t0)
elif TRACK == "exponent":
run_exponent(t0)
else:
raise SystemExit(f"unknown track {TRACK!r} (primary | exponent)")
if __name__ == "__main__":
main()
lib/scaling.py · current file at build (outside the mutable surface) · sha256 54f6d3e5da83…
"""The power-law fit and the extrapolation arithmetic — outside the mutable surface.
``log L = log a - alpha log N``, fitted by ordinary least squares to the SEED
MEANS of the pinned development cells (one point per training-set size N), with
``fit_r2`` on the log scale and a percentile bootstrap interval for alpha that
resamples the seeds WITHIN each N (independently across N; 2,000 draws, a fixed
resampling seed). Within a seed the cells' subsamples are nested
(`lib/protocol.py`), so losses at different N of the same seed are positively
correlated; resampling within N ignores that pairing. That widens the interval
only for the component shared along a seed's whole curve (e.g. its initialization);
for the nested-SUBSAMPLE component the METHOD gate's synthetic checks found the
interval can be too NARROW, so this interval is a descriptive spread, not a
calibrated 95% interval (method_card.md §4; findings must say so). With 3 seeds per
N the resampled mean's variance is also (3-1)/3 of the sample variance of the mean
— a known small-sample shortfall of the percentile bootstrap, stated rather than
corrected.
``tables/scaling_fit.tsv`` carries one row per N (``n_train, n_seeds,
mean_val_mlogloss, std_val_mlogloss, fitted_loss``) and repeats the fit's
parameters on every row (``a, alpha, fit_r2, alpha_ci_low, alpha_ci_high,
predicted_loss_at_full``), so each row is self-contained and the sealed run reads
``a`` and ``alpha`` from any of them (:func:`read_fit` checks they agree).
"""
from __future__ import annotations
import json
import re
from collections.abc import Mapping
from pathlib import Path
from typing import Any
import numpy as np
import pandas as pd
from kleinlib.primitives import sha256_file
CELL_GLOB = "cell_*_s*.tsv"
CELL_NAME_RE = re.compile(r"^cell_(?P<run>.+)_s(?P<seed>-?\d+)\.tsv$")
CELL_COLUMNS = ("run", "seed", "n_train", "val_mlogloss", "best_step")
FIT_TABLE = "tables/scaling_fit.tsv"
FIT_PARAMETER_COLUMNS = ("a", "alpha", "fit_r2", "alpha_ci_low", "alpha_ci_high", "predicted_loss_at_full")
MIN_SIZES = 3
BOOTSTRAP_DRAWS = 2_000
#: A RESAMPLING seed for the bootstrap, not a partition seed: the partitions come
#: from the contract (`kleinlib.data`), and this only orders the resampling draws.
BOOTSTRAP_SEED = 20_261_103
def pinning_manifest(study: Path, rel: str, *, track: str) -> dict[str, Any] | None:
"""The newest ``measured`` manifest of ``track`` that pins ``rel``, or None."""
found = None
for path in sorted((study / "runs").glob("E*/manifest.json")):
manifest = json.loads(path.read_text(encoding="utf-8"))
if manifest.get("track") != track or manifest.get("disposition") != "measured":
continue
if rel in (manifest.get("artifacts") or {}):
found = manifest
return found
def collect_cells(study: Path, *, require_pinned: bool) -> tuple[pd.DataFrame, list[str]]:
"""Every development cell row in ``tables/cell_*_s*.tsv``; ``(rows, notes)``.
With ``require_pinned`` (every real run) a table counts only when the manifest
of the run it names is a ``measured`` development run of the ``primary`` track,
pins this exact path, and the bytes on disk still hash to the pin; a table
from a run that crashed or was discarded is left out and named in ``notes``; a
table with no manifest at all, or whose bytes differ from its pin, stops the
fit (it is not evidence, and silently dropping it would hide why). Without it
(``KLEIN_SMOKE=1`` against synthetic tables) every table counts.
"""
rows: list[pd.DataFrame] = []
notes: list[str] = []
for path in sorted((study / "tables").glob(CELL_GLOB)):
rel = path.relative_to(study).as_posix()
match = CELL_NAME_RE.match(path.name)
if match is None:
raise ValueError(f"{rel}: not a cell table name (cell_<run>_s<seed>.tsv)")
frame = pd.read_csv(path, sep="\t", dtype={"run": str})
missing = [c for c in CELL_COLUMNS if c not in frame.columns]
if missing or len(frame) != 1:
raise ValueError(f"{rel}: expected one row with columns {list(CELL_COLUMNS)}; missing {missing}")
run, seed = str(frame["run"].iloc[0]), int(frame["seed"].iloc[0])
if (run, seed) != (match["run"], int(match["seed"])):
raise ValueError(f"{rel}: holds run {run} seed {seed}, which is not the run its name says")
if require_pinned:
manifest_path = study / "runs" / run / "manifest.json"
if not manifest_path.is_file():
raise ValueError(f"{rel}: no manifest runs/{run}/manifest.json — an unpinned table is not evidence")
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
if manifest.get("track") != "primary" or manifest.get("evaluation_kind", "development") != "development":
raise ValueError(f"{rel}: run {run} is not a development cell of the primary track")
if manifest.get("disposition") != "measured":
notes.append(f"excluded {rel}: run {run} disposition {manifest.get('disposition')!r}")
continue
pinned = (manifest.get("artifacts") or {}).get(rel)
if not pinned:
raise ValueError(f"{rel}: run {run}'s manifest does not pin this table")
if pinned.get("sha256") != sha256_file(path):
raise ValueError(f"{rel}: bytes differ from the sha256 pinned by run {run}")
rows.append(frame[list(CELL_COLUMNS)])
if not rows:
raise ValueError("no development cell tables (tables/cell_*_s*.tsv) to fit")
table = pd.concat(rows, ignore_index=True)
duplicated = table[table.duplicated(["run", "seed"], keep=False)]
if not duplicated.empty:
raise ValueError(f"duplicate (run, seed) cell rows: {duplicated[['run', 'seed']].values.tolist()}")
if not np.all(np.isfinite(table["val_mlogloss"].to_numpy(dtype=float))) or (table["val_mlogloss"] <= 0).any():
raise ValueError("cell losses must be finite and positive for a log-log fit")
return table, notes
def ols_loglog(sizes: np.ndarray, losses: np.ndarray) -> tuple[float, float, float]:
"""``(a, alpha, r2)`` of ``log L = log a - alpha log N`` by least squares."""
x, y = np.log(np.asarray(sizes, dtype=float)), np.log(np.asarray(losses, dtype=float))
slope, intercept = np.polyfit(x, y, 1)
residual = y - (intercept + slope * x)
total = float(np.sum((y - y.mean()) ** 2))
r2 = 1.0 - float(np.sum(residual**2)) / total if total > 0 else float("nan")
return float(np.exp(intercept)), float(-slope), r2
def fit_cells(table: pd.DataFrame, *, n_full: int) -> tuple[pd.DataFrame, dict[str, float]]:
"""Seed means per N, the log-log fit, and the bootstrap interval for alpha."""
groups = {int(n): g["val_mlogloss"].to_numpy(dtype=float) for n, g in table.groupby("n_train")}
sizes = np.array(sorted(groups), dtype=float)
if sizes.size < MIN_SIZES:
raise ValueError(f"the fit needs measured cells at >= {MIN_SIZES} sizes, found {sizes.size}")
means = np.array([groups[int(n)].mean() for n in sizes])
a, alpha, r2 = ols_loglog(sizes, means)
rng = np.random.default_rng(BOOTSTRAP_SEED)
draws = np.empty(BOOTSTRAP_DRAWS)
for i in range(BOOTSTRAP_DRAWS):
resampled = [rng.choice(groups[int(n)], size=groups[int(n)].size, replace=True).mean() for n in sizes]
draws[i] = ols_loglog(sizes, np.array(resampled))[1]
low, high = (float(q) for q in np.quantile(draws, [0.025, 0.975]))
clamped = not (low <= alpha <= high)
params = {
"a": a,
"alpha": alpha,
"fit_r2": r2,
# A percentile interval can, rarely, exclude its own point estimate; it is
# widened to include it and `ci_clamped` says so on the printed block.
"alpha_ci_low": min(low, alpha),
"alpha_ci_high": max(high, alpha),
"ci_clamped": float(clamped),
"predicted_loss_at_full": a * float(n_full) ** (-alpha),
"n_sizes": float(sizes.size),
"n_cell_rows": float(len(table)),
}
per_n = pd.DataFrame(
{
"n_train": sizes.astype(int),
"n_seeds": [groups[int(n)].size for n in sizes],
"mean_val_mlogloss": means,
"std_val_mlogloss": [groups[int(n)].std(ddof=1) if groups[int(n)].size > 1 else 0.0 for n in sizes],
"fitted_loss": a * sizes ** (-alpha),
}
)
for key in FIT_PARAMETER_COLUMNS:
per_n[key] = params[key]
return per_n, params
def write_fit(study: Path, per_n: pd.DataFrame) -> str:
path = study / FIT_TABLE
path.parent.mkdir(parents=True, exist_ok=True)
per_n.to_csv(path, sep="\t", index=False, lineterminator="\n", float_format="%.10g")
return FIT_TABLE
def read_fit(path: Path) -> tuple[float, float]:
"""``(a, alpha)`` from a fit table; raises when it is missing or inconsistent."""
if not path.is_file():
raise FileNotFoundError(
f"{path.name} is missing — a sealed extrapolation without a pinned fit is a crash; "
"run the exponent track first"
)
frame = pd.read_csv(path, sep="\t")
missing = [c for c in ("a", "alpha") if c not in frame.columns]
if missing or frame.empty:
raise ValueError(f"{path.name}: no fit parameters (missing {missing})")
a_values, alpha_values = frame["a"].unique(), frame["alpha"].unique()
if a_values.size != 1 or alpha_values.size != 1:
raise ValueError(f"{path.name}: rows disagree on the fit parameters")
a, alpha = float(a_values[0]), float(alpha_values[0])
if not (np.isfinite(a) and a > 0 and np.isfinite(alpha)):
raise ValueError(f"{path.name}: unusable fit parameters a={a!r}, alpha={alpha!r}")
return a, alpha
def extrapolation(a: float, alpha: float, n: int, measured: float) -> Mapping[str, float]:
"""The law's prediction at ``n`` and the signed relative error of ``measured``.
``extrapolation_rel_error = (measured - predicted) / measured``: positive when
the measured loss is ABOVE the pure power law (the law was optimistic).
"""
predicted = a * float(n) ** (-alpha)
return {"predicted_loss": predicted, "extrapolation_rel_error": (measured - predicted) / measured}
The sealed cell: E0008
Under --final-test the fit pool is train plus development, N is all of it (59,992), and the pinned law is read before
training starts: a missing or altered fit table stops the run in seconds, not after the whole 8437-step budget. The relative error is computed per
seed against the pinned law, and the notary averages it, which is the registered definition that erratum E1 spells out.
analyze.py · executed by E0008 (final_test, track primary) at commit 23f405e00a60 · sha256 ccf9f09a349b…
"""Data-scaling cells, the power-law fit, and the sealed extrapolation — THE mutable surface.
A candidate changes ONE thing: ``CELL["n_train"]`` (the training-set size N of a
`primary` development cell). The training protocol is fixed in `lib/protocol.py`
and the fit arithmetic in `lib/scaling.py`, both outside `entrypoint.mutable`.
Tracks (`KLEIN_TRACK`, set by `klein run-one`):
* ``primary`` — development: the seed (`KLEIN_SEED`; `entrypoint.seeds` makes one
cell a 3-seed array) draws N items of the train partition, holds out 10% as an
inner validation set, trains the fixed protocol, and scores the best
inner-validation checkpoint on the development partition (`val_mlogloss`). It
pins ``tables/cell_<run>_s<seed>.tsv`` (run, seed, n_train, val_mlogloss,
best_step) and the per-seed confusion table.
SEALED (`klein run-one --final-test`, ``KLEIN_EVALUATION_KIND=final_test``):
the fit pool is train + development (60,000) and N is all of it; the test
partition is scored once, and the pinned law ``tables/scaling_fit.tsv`` is
compared with this seed's measured loss (`predicted_loss`,
`extrapolation_rel_error`). It pins ``tables/sealed_<run>_s<seed>.tsv`` — NOT a
``cell_*`` name, so a later fit can never pick up a sealed number.
* ``exponent`` — fits ``log L = log a - alpha log N`` over the seed means of every
pinned development cell and prints alpha with its bootstrap interval
(`scaling_exponent`, `fit_r2`), pinning ``tables/scaling_fit.tsv``. The fit is
deterministic, so the seed array prints three identical blocks.
The partitions come from the contract: `kleinlib.data.load_items()` is the
index-table wrapper of `kleinlib.data.load_partition()`, prints the
`split_fingerprint:` the notary checks, and under ``KLEIN_SEALED_DRYRUN=1``
answers a sealed request with the development partition plus ``sealed_dryrun: 1``.
``KLEIN_SMOKE=1`` is a shape check: N = 300, 30 steps, nothing written. It never
reads the sealed partition (a smoke ``final_test`` must also set
``KLEIN_SEALED_DRYRUN=1``).
"""
from __future__ import annotations
import os
import time
from pathlib import Path
import numpy as np
import pandas as pd
from lib import protocol, scaling # the study's fixed machinery, beside this file
from kleinlib.data import load_items, partition_fingerprints
from kleinlib.dl import report_usage, seed_everything
from kleinlib.eval import evaluate_estimate
from kleinlib.eval_multiclass import evaluate_multiclass, multiclass_metrics
from kleinlib.primitives import sha256_file
from kleinlib.torch_device import pick_device
HERE = Path(__file__).resolve().parent
# --- the candidate: the whole per-experiment diff ------------------------------
CELL = {"n_train": 500}
# -------------------------------------------------------------------------------
SMOKE = os.environ.get("KLEIN_SMOKE") == "1"
DRY_RUN = os.environ.get("KLEIN_SEALED_DRYRUN") == "1"
FINAL = os.environ.get("KLEIN_EVALUATION_KIND") == "final_test"
EXPERIMENT_ID = os.environ.get("KLEIN_EXPERIMENT_ID") or ("SMOKE" if SMOKE else None)
TRACK = os.environ.get("KLEIN_TRACK") or ("primary" if SMOKE else None)
SEED = int(os.environ.get("KLEIN_SEED", "0"))
LABELS = list(range(protocol.N_CLASSES))
def run_primary(t0: float) -> None:
if SMOKE and FINAL and not DRY_RUN:
raise SystemExit("a smoke run never reads the sealed partition: add KLEIN_SEALED_DRYRUN=1")
sealed = FINAL and not DRY_RUN
fit_law = None
if FINAL:
# Read the pinned law BEFORE training: a missing fit crashes in seconds,
# not after the whole full-data budget.
fit_path = HERE / scaling.FIT_TABLE
if not SMOKE:
pin = scaling.pinning_manifest(HERE, scaling.FIT_TABLE, track="exponent")
if pin is None:
raise SystemExit(f"{scaling.FIT_TABLE} is not pinned by a measured exponent run")
if pin["artifacts"][scaling.FIT_TABLE].get("sha256") != sha256_file(fit_path):
raise SystemExit(f"{scaling.FIT_TABLE} differs from the bytes {pin['experiment']} pinned")
fit_law = scaling.read_fit(fit_path)
fit_ids, eval_ids = load_items(study_dir=HERE) # prints split_fingerprint (+ sealed_dryrun)
n_pool = len(fit_ids)
if SMOKE:
n = protocol.SMOKE_N_TRAIN
elif FINAL:
n = n_pool # the full-data cell: every item of the fit pool
else:
n = int(CELL["n_train"])
if sealed and n != protocol.N_FULL:
raise SystemExit(f"the sealed cell must train on N={protocol.N_FULL}, the fit pool holds {n_pool}")
seed_everything(SEED, deterministic=True)
rng = np.random.default_rng(SEED)
fit_pos, inner_pos = protocol.draw_subsample(n_pool, n, rng)
store = protocol.ItemStore(HERE / "data" / "prepared")
x_fit, y_fit = store.load([fit_ids[i] for i in fit_pos])
x_inner, y_inner = store.load([fit_ids[i] for i in inner_pos])
x_eval, y_eval = store.load(eval_ids)
steps = protocol.SMOKE_STEPS if SMOKE else (protocol.DRYRUN_STEPS if DRY_RUN else protocol.steps_for(n))
every = protocol.SMOKE_EVAL_EVERY if SMOKE else protocol.eval_every(steps)
model, info = protocol.train(x_fit, y_fit, x_inner, y_inner, steps=steps, every=every, rng=rng, device=pick_device())
proba = protocol.predict_proba(model, x_eval, next(model.parameters()).device)
report_usage(steps=info["steps"])
extra: dict[str, float | int] = {
"n_train": n,
"n_fit": len(fit_pos),
"n_inner": len(inner_pos),
"steps": info["steps"],
"eval_every": every,
"best_step": info["best_step"],
"best_inner_loss": round(info["best_inner_loss"], 6),
}
if FINAL:
# The measured loss of THIS seed (the same number the block prints).
measured = multiclass_metrics(y_eval, proba, labels=LABELS)[0]["val_mlogloss"]
a, alpha = fit_law
law = scaling.extrapolation(a, alpha, n, measured)
# Per seed: predicted = a * N**(-alpha) at THIS run's N (60,000 on the
# sealed run; the 50,000-item train partition on a dry run, so the
# rehearsal compares like with like), and
# extrapolation_rel_error = (measured - predicted) / measured. The notary
# averages every printed key over the seed array, so the run's
# `extrapolation_rel_error` is the SEED MEAN OF THE PER-SEED RELATIVE
# ERRORS — which differs from (mean measured - predicted) / mean measured
# only at second order in the seed spread (Jensen); P3 and P4 read the
# former. Both are recomputable from the pinned sealed tables.
extra.update({"fit_a": a, "fit_alpha": alpha, **law})
# Under the seed array the evaluator pins tables/confusion_<run>_s<seed>.tsv itself.
writes = not (SMOKE or DRY_RUN) # the dry run must leave the tree as it found it
value = evaluate_multiclass(
y_eval, proba, labels=LABELS, exp_id=EXPERIMENT_ID, metric_name="val_mlogloss", t0=t0,
fit_seconds=info["fit_seconds"], train_n=len(fit_pos), extra=extra,
study_dir=HERE if writes else None,
)
if writes:
row = {"run": EXPERIMENT_ID, "seed": SEED, "n_train": n, "val_mlogloss": f"{value:.6f}", "best_step": info["best_step"]}
if FINAL:
name = f"tables/sealed_{EXPERIMENT_ID}_s{SEED}.tsv"
row.update({k: f"{float(extra[k]):.10g}" for k in ("fit_a", "fit_alpha", "predicted_loss", "extrapolation_rel_error")})
else:
name = f"tables/cell_{EXPERIMENT_ID}_s{SEED}.tsv"
(HERE / "tables").mkdir(parents=True, exist_ok=True)
pd.DataFrame([row]).to_csv(HERE / name, sep="\t", index=False, lineterminator="\n")
print(f"artifact: {name}")
def run_exponent(t0: float) -> None:
if FINAL:
raise SystemExit("the exponent track takes no sealed run (its confirmation is a replication)")
table, notes = scaling.collect_cells(HERE, require_pinned=not SMOKE)
for note in notes:
print(f"note: {note}")
per_n, params = scaling.fit_cells(table, n_full=protocol.N_FULL)
# The fit's inputs were measured on the development partition; print its
# fingerprint so the notary can hold the fit to the same rows.
fingerprint = partition_fingerprints(HERE)["development"]
if not SMOKE:
rel = scaling.write_fit(HERE, per_n)
print(f"artifact: {rel}")
evaluate_estimate(
params["alpha"], params["alpha_ci_low"], params["alpha_ci_high"], int(params["n_cell_rows"]),
exp_id=EXPERIMENT_ID, metric_name="scaling_exponent", metric_goal="higher", t0=t0,
extra={
"fit_r2": params["fit_r2"],
"a": params["a"],
"n_sizes": int(params["n_sizes"]),
"predicted_loss_at_full": params["predicted_loss_at_full"],
"ci_clamped": int(params["ci_clamped"]),
},
split_fingerprint=fingerprint,
study_dir=None if SMOKE else HERE,
)
def main() -> None:
if EXPERIMENT_ID is None or TRACK is None:
raise SystemExit("run through `klein run-one` (or KLEIN_SMOKE=1 for a shape check)")
t0 = time.time()
if TRACK == "primary":
run_primary(t0)
elif TRACK == "exponent":
run_exponent(t0)
else:
raise SystemExit(f"unknown track {TRACK!r} (primary | exponent)")
if __name__ == "__main__":
main()
lib/protocol.py · current file at build (outside the mutable surface) · sha256 467d063392bc…
"""The FIXED training protocol of every cell — outside the mutable surface.
`analyze.py` is the per-experiment surface and a cell sets only
`CELL["n_train"]`. Everything that decides HOW a cell trains lives here, so the
diff of a cell can change the data budget N and nothing else; a change to this
file is a deliberate, recorded protocol change, never part of a candidate.
The protocol, in one paragraph
------------------------------
The network is a small 3-conv CNN with global average pooling
(:data:`ARCHITECTURE`, 23,946 parameters): two max-pool stages give each conv3
unit an 18x18-pixel receptive field (3 -> 4 -> 8 -> 10 -> 18, stride 4), averaged by
global pooling over a 7x7 grid that tiles the image — the recipe's
two-block variant pools globally at 14x14 after two 3x3 convolutions, which
leaves it a bag of 6x6 local textures. Pixels are divided by 255; no
augmentation, no normalization layer, no dropout, PyTorch's default
initialization. A seed draws a uniformly random subsample of N items from the
fit pool; 10% of it (:func:`inner_size`) is held out as an INNER validation set
and the remaining 90% is trained on with AdamW (lr 1e-3, weight decay 1e-4),
batch 128, for :func:`steps_for` optimizer steps (20 epochs of the 90%, at least
400, at most 12,000). The inner-validation cross-entropy is measured every
:func:`eval_every` steps and at the last step; the checkpoint with the lowest
inner loss is kept in memory and is the one that is scored. Batches are streamed
index-shuffles (`kleinlib.torch_loop.iterate_minibatches`, war story 2) — no
DataLoader, no TensorDataset. Torch runs on 1 thread (TORCH_THREADS).
Sources of randomness (all from the one integer `KLEIN_SEED`): the subsample and
its inner split (``numpy.random.default_rng(seed).permutation``), the minibatch
order (the same generator, continued), and the weight initialization
(``kleinlib.dl.seed_everything(seed, deterministic=True)``). Within one seed the
subsamples are NESTED across N: the N-item subsample is the first N entries of
the seed's permutation of the pool, and its fit set is the first 90% of those, so
fit(N=500) ⊂ fit(N=1,000) ⊂ … for the same seed (common random numbers along the
learning curve). Different seeds draw different permutations, so data-sampling
variance is inside every cell.
Known nondeterminism: CPU float reductions under a different thread count or
oneDNN build can move a loss in its last digits; the replication tolerance, not
bitwise identity, is the bar (`references/compute-and-devices.md`).
"""
from __future__ import annotations
import time
from collections.abc import Sequence
from pathlib import Path
from typing import Any
import numpy as np
import pandas as pd
# --- the protocol constants ---------------------------------------------------
ARCHITECTURE = (
"cnn3-gap: conv3x3(1->16)+ReLU+maxpool2 -> conv3x3(16->32)+ReLU+maxpool2 -> "
"conv3x3(32->64)+ReLU -> global average pool -> linear(64->10); 23,946 parameters"
)
CHANNELS: tuple[int, int, int] = (16, 32, 64)
N_PARAMETERS = 23_946
N_CLASSES = 10
IMAGE_SHAPE = (28, 28)
PIXEL_SCALE = 255.0 # pixels / 255; no augmentation, no normalization
OPTIMIZER = "AdamW"
LEARNING_RATE = 1e-3
WEIGHT_DECAY = 1e-4
BATCH_SIZE = 128
EPOCHS = 20 # of the 90% fit share
MIN_STEPS = 400
MAX_STEPS = 12_000
INNER_VALIDATION_FRACTION = 0.10 # of the N-item subsample, held out for checkpoint selection
EVAL_EVERY_MIN = 50
EVAL_POINTS = 40 # eval_every = max(EVAL_EVERY_MIN, steps // EVAL_POINTS)
TORCH_THREADS = 1 # 4 is ~2x faster on a quiet machine but 15-30x slower when sibling studies train (instrument report); 1 is robust
SCORE_BATCH = 1_000 # items per forward pass when scoring (speed only)
#: The sealed cell trains on the whole fit pool (official train = train + development):
#: 60,000 rows minus the 8 development near-copies prepare.py removes (DATA gate).
N_FULL = 59_992
# --- the smoke budget (KLEIN_SMOKE=1 only — a shape check, never evidence) -----
SMOKE_N_TRAIN = 300
SMOKE_STEPS = 30
SMOKE_EVAL_EVERY = 10
# --- the sealed dry run (KLEIN_SEALED_DRYRUN=1): a rehearsal of the PATH, not a measurement ---
# A full-budget training at N=50,000 would preview the extrapolation on development data; the
# rehearsal needs only that every step of the sealed path runs, so it trains this many steps.
DRYRUN_STEPS = 60
def inner_size(n: int) -> int:
"""Items of an N-item subsample held out as the inner validation set."""
inner = int(round(INNER_VALIDATION_FRACTION * n))
if inner < 1 or inner >= n:
raise ValueError(f"N={n} is too small to hold out an inner validation set")
return inner
def steps_for(n: int) -> int:
"""``max(400, ceil(20 epochs * 0.9N / 128))``, capped at 12,000."""
n_fit = n - inner_size(n)
epochs_steps = -(-EPOCHS * n_fit // BATCH_SIZE) # integer ceil
return min(MAX_STEPS, max(MIN_STEPS, epochs_steps))
def eval_every(steps: int) -> int:
"""Inner-validation cadence: every ``max(50, steps // 40)`` steps (and the last step)."""
return max(EVAL_EVERY_MIN, steps // EVAL_POINTS)
def draw_subsample(n_pool: int, n: int, rng: np.random.Generator) -> tuple[np.ndarray, np.ndarray]:
"""``(fit_positions, inner_positions)`` into a pool of ``n_pool`` items.
The subsample is the first ``n`` entries of one permutation of the pool; its
first ``n - inner_size(n)`` are trained on and the rest are the inner
validation set. Consumes exactly one permutation draw from ``rng``.
"""
if not 1 < n <= n_pool:
raise ValueError(f"N={n} must lie in (1, {n_pool}] (the fit pool)")
chosen = rng.permutation(n_pool)[:n]
n_fit = n - inner_size(n)
return chosen[:n_fit], chosen[n_fit:]
class ItemStore:
"""The prepared payload, addressed by item id (`data/prepared/images.npy` + `index.csv`)."""
def __init__(self, prepared_dir: Path) -> None:
index = pd.read_csv(prepared_dir / "index.csv", dtype={"id": str}, keep_default_na=False)
self._row = pd.Series(np.arange(len(index)), index=index["id"].to_numpy())
self._label = index["label"].to_numpy(dtype=np.int64)
self._images = np.load(prepared_dir / "images.npy", mmap_mode="r")
if self._images.shape != (len(index), *IMAGE_SHAPE) or self._images.dtype != np.uint8:
raise ValueError(
f"images.npy is {self._images.dtype} {self._images.shape}; expected uint8 "
f"({len(index)}, {IMAGE_SHAPE[0]}, {IMAGE_SHAPE[1]}) — re-run prepare.py"
)
def load(self, ids: Sequence[str]) -> tuple[np.ndarray, np.ndarray]:
"""``(x, y)``: float32 (n, 1, 28, 28) in [0, 1] and int64 labels, in ``ids`` order."""
rows = self._row.loc[list(ids)].to_numpy()
x = np.asarray(self._images[np.sort(rows)], dtype=np.float32)
order = np.argsort(np.argsort(rows)) # mmap reads are fastest sorted; restore ids order
x = x[order] / np.float32(PIXEL_SCALE)
return x[:, None, :, :], self._label[rows]
def build_model():
"""The fixed network (:data:`ARCHITECTURE`)."""
from torch import nn
c1, c2, c3 = CHANNELS
model = nn.Sequential(
nn.Conv2d(1, c1, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2), # 28 -> 14
nn.Conv2d(c1, c2, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2), # 14 -> 7
nn.Conv2d(c2, c3, 3, padding=1), nn.ReLU(),
nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(c3, N_CLASSES),
)
count = sum(p.numel() for p in model.parameters())
if count != N_PARAMETERS:
raise RuntimeError(f"the fixed network has {count} parameters, the protocol states {N_PARAMETERS}")
return model
def _mean_cross_entropy(model, x, y, device) -> float:
import torch
from torch import nn
total = 0.0
with torch.no_grad():
for start in range(0, len(x), SCORE_BATCH):
logits = model(x[start : start + SCORE_BATCH].to(device))
target = y[start : start + SCORE_BATCH].to(device)
total += float(nn.functional.cross_entropy(logits, target, reduction="sum"))
return total / len(x)
def train(
x_fit: np.ndarray,
y_fit: np.ndarray,
x_inner: np.ndarray,
y_inner: np.ndarray,
*,
steps: int,
every: int,
rng: np.random.Generator,
device: Any,
) -> tuple[Any, dict[str, Any]]:
"""Train the fixed network; return it at its best inner-validation checkpoint.
The caller seeds torch (``seed_everything``) before calling; ``rng`` orders
the minibatches.
"""
import torch
from torch import nn
from kleinlib.torch_loop import iterate_minibatches
torch.set_num_threads(TORCH_THREADS)
model = build_model().to(device)
optimizer = torch.optim.AdamW(model.parameters(), lr=LEARNING_RATE, weight_decay=WEIGHT_DECAY)
xt, yt = torch.from_numpy(x_fit), torch.from_numpy(y_fit)
xi, yi = torch.from_numpy(x_inner), torch.from_numpy(y_inner)
best_loss, best_step, best_state = float("inf"), 0, None
evaluations = 0
step = 0
started = time.time()
model.train()
while step < steps:
for batch in iterate_minibatches(len(xt), BATCH_SIZE, shuffle=True, generator=rng):
index = torch.from_numpy(batch)
optimizer.zero_grad(set_to_none=True)
loss = nn.functional.cross_entropy(
model(xt.index_select(0, index).to(device)), yt.index_select(0, index).to(device)
)
if not torch.isfinite(loss):
raise FloatingPointError(f"non-finite training loss at step {step + 1}")
loss.backward()
optimizer.step()
step += 1
if step % every == 0 or step == steps:
model.eval()
inner = _mean_cross_entropy(model, xi, yi, device)
model.train()
evaluations += 1
if not np.isfinite(inner):
raise FloatingPointError(f"non-finite inner-validation loss at step {step}")
if inner < best_loss:
best_loss, best_step = inner, step
best_state = {k: v.detach().to("cpu", copy=True) for k, v in model.state_dict().items()}
if step >= steps:
break
if best_state is None: # pragma: no cover - steps >= 1 always evaluates at the last step
raise RuntimeError("no inner-validation checkpoint was evaluated")
model.load_state_dict(best_state)
model.eval()
return model, {
"steps": step,
"best_step": best_step,
"best_inner_loss": best_loss,
"inner_evaluations": evaluations,
"fit_seconds": time.time() - started,
}
def predict_proba(model, x: np.ndarray, device: Any) -> np.ndarray:
"""Softmax probabilities (float64, rows renormalized to sum to 1)."""
import torch
chunks = []
with torch.no_grad():
for start in range(0, len(x), SCORE_BATCH):
logits = model(torch.from_numpy(x[start : start + SCORE_BATCH]).to(device))
chunks.append(torch.softmax(logits.double(), dim=1).cpu().numpy())
proba = np.concatenate(chunks)
return proba / proba.sum(axis=1, keepdims=True)
There is no declared verifier on this study: the evaluator kleinlib.eval_multiclass computes the cross-entropy and the notary reads the
printed block, so the training script does not grade itself on a number it chose. The step rule is the single line to look at, because it
produced the shared budget:
def steps_for(n: int) -> int:
"""max(400, ceil(20 epochs * 0.9N / 128)), capped at 12,000."""
n_fit = n - inner_size(n)
epochs_steps = -(-EPOCHS * n_fit // BATCH_SIZE) # integer ceil
return min(MAX_STEPS, max(MIN_STEPS, epochs_steps))
Pitfalls and war stories that bit this study
A minimum step count is a hidden compute confound. The
max(400, …)floor gave N=500, 1,000 and 2,000 the same 400 steps (113.8, 56.9 and 28.4 epochs) while every cell from N=4000 up trained 20 epochs, and every best checkpoint landed in the last 5 percent of its budget (C6). Whether this shaped the flat left end is the untested hypothesis C9. The recipe advice that follows from the measured part is C13: make the step budget grow with N across the whole range and check that no best checkpoint sits at the end of its budget.A good in-range fit is not a forecast. R² failed here, but even a fit that passed could not have said which way it would miss. Hold the law to a sealed extrapolation point (C14). The signed miss of −0.2802 and the post-hoc best case of −0.0745 show that the sign you expect from theory can be the wrong one (C17).
Nested subsamples narrow the bootstrap. Resampling seeds within each N ignores the pairing along a seed's curve, so the printed bootstrap width (0.0230) was 2.33 times narrower than the per-seed-slope t-interval (0.0536). Report both (C15). An early docstring claimed the bootstrap “errs wide”; the METHOD-gate synthetic checks withdrew that before any cell ran.
Score the fit and the extrapolation on the same distribution. Here the fit cells used the development lane and the sealed cell the test set (C16). A control that trains at a large N and scores the development lane would split the miss into law and partition parts.
A tooling false positive nearly blocked the study. A 64-bit hash audit flagged most held-out silhouettes as duplicates; an exact pixel-space criterion cleared it and removed the 8 and 5 genuine near-copies (section 3).
Rehearse the sealed run. The sealed access can be spent once per track. The sealed dry run, which trains 60 steps on development data and spends nothing, exists so that a crash in the path cannot burn the only access; this study ran it twice before the real run.
Detached cells are attested, not observed. Run a re-execution of the cell you care about under observation; here that was done for E0005 within the claims' evidence.
Do not let the notebook outrun the claim. Three early program.md entries read the compute-limited mechanism as fact. The claim C9 was kept at “hypothesis, untested” and the notebook was annotated, not rewritten.
Hardware and cost
4-CPU x86_64 Linux VM, no GPU, torch CPU path, one thread. The sealed 3-seed array took 1883.8 s of wall time. Wall time is informational, not a budget; the budget is steps.
Next steps & references
What to try next
- Step-extended small cells (tests C9). Re-run N=500, 1000 and 2000 with a step budget at least as large as the N=4000 cell's, 3 seeds each, same development lane. If the left end then declines and the six-cell exponent steepens, the compute-limited reading gains support; if it stays flat, the small-data-region reading does.
- A same-partition extrapolation control (tests C11 and C16). Train at a large N on the train lane and score the development lane, so the miss splits into its law and partition parts.
- Register a two-regime or floor law before data. Pre-register a smoothly broken power law or an fit on the same six cells and hold it against a fresh sealed point between N=16000 and the full pool; never refit on E0008. Run a shuffled-label negative control in the same study.
- Longer full-pool training (follows P7). The full-pool best checkpoint sits in the last 5 percent of its budget; measure how far the loss keeps falling with a larger budget to learn whether 0.3959 is data-limited or compute-limited.
References
All sixteen entries in the method card are verified (arXiv, Crossref or proceedings records checked on 2026-11-03); none is promoted from unverified.
- Xiao, Rasul & Vollgraf 2017. Fashion-MNIST: a Novel Image Dataset for Benchmarking Machine Learning Algorithms. arXiv:1708.07747.
- Cortes, Jackel, Solla, Vapnik & Denker 1993. Learning Curves: Asymptotic Values and Rate of Convergence. NIPS 6, pp. 327-334.
- Hestness et al. 2017. Deep Learning Scaling is Predictable, Empirically. arXiv:1712.00409.
- Rosenfeld, Rosenfeld, Belinkov & Shavit 2020. A Constructive Prediction of the Generalization Error Across Scales. ICLR 2020, arXiv:1909.12673.
- Kaplan et al. 2020. Scaling Laws for Neural Language Models. arXiv:2001.08361.
- Hoffmann et al. 2022. Training Compute-Optimal Large Language Models. NeurIPS 2022, arXiv:2203.15556.
- Bahri, Dyer, Kaplan, Lee & Sharma 2024. Explaining neural scaling laws. PNAS 121(27) e2311878121, doi:10.1073/pnas.2311878121.
- Viering & Loog 2023. The Shape of Learning Curves: A Review. IEEE TPAMI 45(6) 7799-7819, doi:10.1109/TPAMI.2022.3220744.
- Alabdulmohsin, Neyshabur & Zhai 2022. Revisiting Neural Scaling Laws in Language and Vision. NeurIPS 2022, arXiv:2209.06640.
- Caballero, Gupta, Rish & Krueger 2023. Broken Neural Scaling Laws. ICLR 2023, arXiv:2210.14891.
- Besiroglu, Erdil, Barnett & You 2024. Chinchilla Scaling: A replication attempt. arXiv:2404.10102.
- Hoiem, Gupta, Li & Shlapentokh-Rothman 2021. Learning Curves for Analysis of Deep Networks. ICML 2021, arXiv:2010.11029.
- Nakkiran et al. 2020. Deep Double Descent: Where Bigger Models and More Data Hurt. ICLR 2020, arXiv:1912.02292.
- Clauset, Shalizi & Newman 2009. Power-law distributions in empirical data. SIAM Review 51(4) 661-703, doi:10.1137/070710111.
- Loshchilov & Hutter 2019. Decoupled Weight Decay Regularization. ICLR 2019, arXiv:1711.05101.
- Efron & Tibshirani 1993. An Introduction to the Bootstrap. Chapman & Hall, doi:10.1007/978-1-4899-4541-9.