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 L(N) = a\,N^{-\alpha} to the held-out cross-entropy at six training-set sizes, N = 500, 1000, 2000, 4000, 8000, 16000, 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

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

  1. The exponent is shallow and the pure law is a poor description. The fit gives \alpha = 0.1304 with log-log R^2 = 0.7955, far under the registered 0.98 (claims C1, C2). The three smallest cells are flat where a power law needs a decline.
  2. 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).
  3. 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:

L(N) = a\,N^{-\alpha}\qquad\Longleftrightarrow\qquad \ln L = \ln a - \alpha \ln N

Each cell is a 3-seed array and the fit uses the seed mean \bar{L}_k = \tfrac{1}{3}\sum_{s=0}^{2} L_{k,s} of the development cross-entropy at each of the six sizes. R² is computed in log space. The printed interval for \alpha 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

L(N) = L_{\infty} + b\,N^{-\beta}

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:

e = \frac{L_{\mathrm{measured}} - L_{\mathrm{predicted}}}{L_{\mathrm{measured}}},\qquad L_{\mathrm{predicted}} = a\,N_{\star}^{-\alpha},\quad N_{\star} = 59992

A positive e means the law was optimistic. P3 asks whether |e| \le 0.20, P4 whether e > 0, and P6 whether e 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

\text{steps}(N) = \min\!\Big(12000,\ \max\!\big(400,\ \lceil 20\, n_{\mathrm{fit}} / 128 \rceil\big)\Big)

optimizer steps, where n_{\mathrm{fit}} 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

PartitionRowsDefined byUsed for
train50,000official train rows 0 to 49,999every development cell draws its N-image subsample from here
development9,992official train rows 50,000 to 59,999, minus 8 near-copiesscores the six fit cells
test (sealed)9,995official t10k, minus 5 near-copiesscored 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

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)

ExpTrackKindMetricStatusDescription
E0001primarydevelopment0.829647333333measuredcell N=500; registered cell measured
E0002primarydevelopment0.949174333333measuredcell N=1000; registered cell measured
E0003primarydevelopment0.840758666667measuredcell N=2000; registered cell measured
E0004primarydevelopment0.756999333333measuredcell N=4000; registered cell measured
E0005primarydevelopment0.652339666667measuredcell N=8000; registered cell measured
E0006primarydevelopment0.563684measuredcell N=16000; registered cell measured
E0007exponentdevelopment0.13036measuredfit: the power law over the six cells; registered cell measured
E0008primaryfinal_test0.395864measuredsealed 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)

Dot plot of the seven primary-track runs in order: six development cells falling from about 0.83 at N=500 through a bump at N=1000 to about 0.56 at N=16000, and the sealed cell at about 0.40 in a separate confirmation band.
Primary track, run by run: seed mean and seed min-to-max of val_mlogloss for the six development cells (E0001 to E0006, scored on the development lane) and, in the separate confirmation band, the sealed full-pool cell E0008 (scored on the official test set). There is no frontier to climb on a registered track; the takeaway is the non-monotone start, N=1000 above N=500. Close

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.

Three lines, one per seed, each rising from N=500 to N=1000 and then falling steadily to N=16000.
Each seed's own loss curve across the six development cells (development lane). Subsamples are nested within a seed, so the three curves are paired. All three rise from N=500 to N=1000, then decline together; the curves converge as N grows. Close

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.

One point for the fitted exponent with a short bootstrap bar, inside the wide shaded P1 range but below the hatched P5 range.
Exponent track, one registered cell (E0007, development cells): the fitted alpha with its printed bootstrap spread against the two registered ranges. It sits inside P1 (supported) and below P5 (refuted); the spread is descriptive, not a calibrated interval. Close

The scaling picture: six cells, one law, one sealed point

Log-log plot of cross-entropy against training-set size. Six development points trace a bumpy line; the fitted power law is a straight line extended as a dashed segment past N=16000 to a prediction marker well above the sealed measured star.
Log-log scaling plot: six development cells (grey seeds, black seed means, E0001 to E0006, development lane), the pinned power law from E0007 (solid in range, dashed extrapolated), and at N=59,992 the sealed cell E0008 (test set) against the law's prediction. The sealed measurement falls below the prediction, and the sealed cell sits on a different partition from the fit cells (C16). Close

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
17 locked in claims.lock
by strength
confirmed 5 · exploratory 12
by class
empirical-description 7 · mechanism-interpretation 2 · procedural-verdict 3 · research-discipline 5
errata
2 of 17 claims tagged · 2 erratum record(s) in the lock
locked at
68dc7756e919 · klein 2.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

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.

The same log-log scaling plot of six development cells, the fitted law and the sealed point.
The headline picture again (development cells on the development lane, sealed cell on the test set): the law fitted on N from 500 to 16,000 lands above the sealed measurement at the full pool. The partition difference means the gap cannot be split exactly between law and partition (C16). Close

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).

Step budget and best-checkpoint step against N on log-log axes; the two lines are nearly identical, flat at 400 steps up to N=2000, then rising to 8437 at the full pool.
Optimizer steps per cell and seed-mean best inner-validation checkpoint step against N, for the six development cells and the sealed cell. The best checkpoint hugs the end of every budget, and N=500, 1,000 and 2,000 share one 400-step budget, so the cells are not matched in compute. Close

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

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

  1. 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.

  2. 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).

  3. 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.

  4. 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.

  5. 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).

  6. 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.

  7. 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.

  8. 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

  1. 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.
  2. 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.
  3. Register a two-regime or floor law before data. Pre-register a smoothly broken power law or an L_{\infty} + b N^{-\beta} 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.
  4. 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.