The Question

Every training recipe carries folklore: warm up the learning rate, tie the input and output embeddings, add dropout, make the model bigger. Each piece of folklore has a paper behind it. None of those papers ran at the budget most people actually train under — a fixed, small number of optimizer steps, decided in advance, spent once. This study asks the folklore's question honestly: under a fixed 2000-step training budget on a character-level corpus, which single-change training-recipe edits to a small char transformer improve held-out validation loss by more than the measured run-to-run floor, when every checkpoint is scored by a verifier the training script cannot touch?

The deliberate constraint. Compute is held fixed in optimizer steps, not in wall-clock seconds, so a candidate cannot buy an improvement by running longer on faster hardware — a CPU run and an accelerator run of the same recipe are the same experiment. And the checkpoint that decides every disposition is never scored by the script that trained it: a second, independent program loads the saved weights from disk, rebuilds the architecture from its own separate implementation, and recomputes the loss. The trainer's own number is recorded beside the checker's, and the two are compared — the searcher is never the one who grades the search.

Four textbook levers were registered as predictions before any of them ran, one per research question:

  1. RQ1 — the recipe contest. Which of warmup, weight tying, dropout and width clears the measured floor at 2000 steps, and which is indistinguishable from re-running the same recipe under a different seed? Prior: at most one — width — clears it, because capacity is the only one of the four that buys anything the optimizer can spend the steps on (source: uninformed — no edit besides the anchor had run before this contract).
  2. RQ2 — does the checker agree with the searcher? Does a verifier that re-scores a checkpoint from disk agree with the training script's own reported loss, and does the same checkpoint survive a device change? Prior: same-device agreement lands orders of magnitude inside the declared tolerance; a device change moves a full re-execution by less than one fit-noise standard deviation (source: scouted — a design-time CPU/MPS pair).
  3. RQ3 — recipes or noise? How large is the largest recipe effect against the anchor's own seed-to-seed spread — is this study measuring recipes, or measuring noise? Prior: a small multiple of the fit-noise standard deviation, not an order of magnitude (source: uninformed).

Six predictions, one arithmetic rule each, registered before any evidence existed:

P#LeverRule on the verifier's printed block
P1the anchor recipe at a seed the floor sweep never usedanchor_z <= 2
P2linear learning-rate warmupdelta_in_floors >= 1
P3weight tying (output head shares the token embedding)abs(delta_in_floors) < 1
P4dropout 0.1delta_in_floors <= -1
P5width 128 → 256delta_in_floors >= 1
P6the sealed final tenth of the corpusabs(sealed_gap_in_fit_noise) <= 2

Every rule is written in units of a floor measured before any candidate ran: a paired-comparison spread across ten redraws of five identically-configured anchor checkpoints, re-scored on identical validation windows. Nothing here is compared against an untuned baseline — the anchor recipe is the reference, and it was tuned no more than any candidate was.

Why this exhibit exists. This is the first Klein study run under the ml-research profile with a closed loop — consult through tutorial — and its literature scorecard is the first entry in knowledge/domains/ml-research/. Two of its three research-question priors are marked uninformed for exactly that reason: there was no prior study to draw on. What follows is the record of what four decades of transformer folklore predicted, and what a fixed step budget, a separate checker, and a measured floor actually found.

The Method

The model, in one paragraph. A character-level language model is a lookup table plus a mixer. Every one of the 65 characters in the vocabulary gets a 128-dimensional vector; a stack of four pre-norm transformer blocks lets each position mix in information from the positions before it — never after, which is what “causal” means; a final linear layer turns each mixed vector back into a score for each of the 65 characters. Train it to put probability on the character that actually comes next, and the loss it reports is the average surprise, in nats, of the next character given everything before it in the window.

\mathcal{L}(\theta) = -\frac{1}{|W|\,T}\sum_{s \in W}\sum_{k=0}^{T-1} \log p_\theta\big(x_{s+k+1} \,\text{given}\, x_{s},\dots,x_{s+k}\big)

where W is the complete, non-overlapping tiling of the evaluation range into windows of T=128 characters — no sampling, no seed. A model that has learned nothing scores a uniform 4.174387 nats (\ln 65); one that has learned only which characters are common scores 3.307264, an add-one unigram fitted on the train partition alone. Anything below that is the model actually using context.

The budget, in one paragraph. The honest way to compare training recipes is at matched compute, and the honest unit of compute is optimizer steps, not seconds — a step is the same amount of arithmetic on a laptop CPU and on an accelerator; a second is not. Every candidate here runs for exactly 2000 steps of 32 windows of 128 characters, and the guardrail that enforces it does not read train.py — it reads the step count back out of the saved checkpoint. That is the difference between a budget and a promise.

The verifier — the idea this study exists to demonstrate. Almost every training script in the world computes its own validation loss and prints it, and that number is then the thing everyone believes. But a training script has a thousand ways to be quietly wrong about it — an evaluation batch drawn from the training range, a target sequence never shifted, a checkpoint saved one step later than the loss was measured, a dropout mask left on at evaluation. So this study separates the searcher from the checker. train.py trains and saves a checkpoint. A second, immutable program, verify.py, then runs in its own process: it loads that checkpoint from disk, asks the contract — never the training script — which characters are the validation partition, rebuilds the model from the checkpoint’s own config with its own independent implementation of the architecture, and recomputes the loss from scratch. The checker’s number is the one the study uses. The trainer’s own estimate is recorded beside it, and if the two disagree by more than 0.01 nats the run is a crash — not a result to be argued about. The person who ran the assay does not also certify the standard.

Weight tying, and why the parameter count is the wrong quantity

One recipe edit shares the output layer with the input embedding instead of giving it independent weights:

\ell = E^{T} h

with E the token-embedding matrix. Tying removes one whole weight matrix, which sounds like a free parameter saving — and it is, at the word-level vocabularies of tens of thousands where the original result was measured, because the same matrix is most of the model and each row is seen rarely. At a 65-character vocabulary the table is tiny and every row is seen constantly, and tying forces one matrix to serve as both the input lookup and the output classifier with no logit scale to reconcile the very different norms the two roles want. Whether that mechanism holds is exactly what this study measures, in the journey section below.

The keep rule, in floors

A candidate improves the frontier only if it clears a bar measured, not guessed, at Phase 0 — the spread between two independently seeded runs of the same recipe, re-scored on identical validation windows, across the ten unordered pairs of five such checkpoints:

\mathcal{L}_{\text{incumbent}} - \mathcal{L}_{\text{candidate}} \ge \delta, \qquad \delta = \max\left(2\,\hat\sigma_{\text{paired}},\ \tfrac{1}{2}\,\mathrm{range}_{\text{paired}}\right)

Every registered prediction below is written as an integer count of \delta, fixed before \delta itself was known.

Three deliberate design choices, and what each costs

  1. The checker re-implements the architecture instead of importing model.py. Cost: duplicated code, and the architecture family becomes part of the contract — a candidate that changes the module tree produces an artifact the checker cannot load, and the run crashes. Benefit: the checker cannot be edited by the search. Two implementations that agree are evidence; one implementation compared with itself is not.
  2. The evaluation is a complete tiling, not sampled batches. Cost: the first character of every window is predicted from no context at all, and the last partial window of each partition is read as context but never scored. Benefit: the trainer’s number and the checker’s number are the same deterministic quantity, so the verifier tolerance can guard float and device drift rather than hide a real disagreement inside a fit-noise-sized fudge factor.
  3. The budget is steps, not seconds. Cost: a wider model gets the same number of steps and therefore more arithmetic per step — not the compute-optimal frontier of scaling-law doctrine, which grows model size and data together. Benefit: the comparison is device-independent and reproducible on a CPU in CI.

The regime this study sits in is small on every axis: 891904 training characters, an 824320-parameter model, a 2000-step budget with a 128-character evaluation context. What that regime does to four textbook levers is the rest of this report.

The Data

Source and shape. The corpus is tinyshakespeare, bundled inside the repository and re-derived by prepare.py against the packager’s published sha256 on every run — 1115394 characters, pure ASCII, a 65-character vocabulary (\n, space, punctuation, and upper- and lower-case letters). Public-domain text, packaged by karpathy/char-rnn under an MIT-declared README.

The prepared artifact is a block index, not a feature table. One row per contiguous 1024-character block, 1089 rows in total — not one row per training example. A character language model’s real target is the next character, which no column can hold, so the contract names a placeholder column (n_chars) purely so the splitter has something to drop. A generic tabular profiler reads that placeholder as a 0.09%-minority “imbalanced target”; nothing in this study ever predicts it, and the data card exists partly to say so in writing before that misreading can propagate anywhere.

The split: contiguous blocks, ordered in time

The corpus is ordered natural language, so partitions are character-offset ranges, never a shuffle — a shuffled split would let a training window straddle a boundary and read the second half of a sentence whose first half sits in a different partition.

PartitionBlocksCharactersShare
train87189190479.96%
development10911161610.01%
sealed final test10911187410.03%

All three are contiguous, verified by prepare.py at write time. Klein’s development fingerprint covers train + development — the first 90% of the corpus — and the sealed final tenth is opened exactly once. Every fingerprint (prepared data, split policy, both realized partitions) is frozen at the DATA gate and every run prints its own realized split_fingerprint back for the notary to compare.

The leak detector: hash the content, not the position

Each block also carries a group id: the sha256 prefix of its normalized text — casefolded, whitespace collapsed. Hashing content instead of a trivial block-position id gives the check teeth: it would fail if the same passage reappeared in two partitions under a cosmetic case or spacing difference. It found nothing to flag — every one of the 1089 blocks stays inside one partition. A second, finer-grained audit measures Jaccard similarity of character 8-grams across partitions:

Later partitionCompared againstMax Jaccard
developmenttrain0.023131
sealedtrain + development0.030059

The largest similarity any held-out block has to anything the model may train on is an overlap of common English 8-grams, not of content. There is nothing to memorize across the split.

Four eval-harness controls, run through the study’s own scoring path

A tabular profiler has nothing to check on an index table with no features and no real target, so the harness itself was audited by feeding it four known predictors and checking that a correct harness scores each one where theory says it must:

ControlRoleScore (nats/char)Verdict
uniformnegative — chance4.174388PASS
untrained networknegative — no information4.305432PASS
add-one unigrampositive — real information3.306991PASS
copy-the-inputnegative — off-by-one detector4.750043PASS

The last row is the interesting one. A predictor that bets the next character equals the current one has no business scoring near chance either way — a correct harness must score it worse than chance, because it is confidently wrong on every character where the text actually changes. If the harness aligned targets with inputs by one position instead of shifting them, that same predictor would score exactly \ln 2 = 0.693147 nats, which is the classic off-by-one bug this control exists to catch. All four controls PASS, and the diagnostic rate of the model’s predicted character actually matching the one just read is 0.024523, not 1.0.

Go / no-go

No BLOCKER is open. Two WARNs are accepted and disclosed rather than fixed, because both are identical for every candidate and both are pinned by the eval_context guardrail: the fixed 128-character evaluation window handicaps the first predicted character of every window with no context at all, and the final partial window of each partition is read as context but never scored. Neither can favor one candidate over another, so both cancel in every comparison this study makes. In particular there is no literal split seed anywhere in an evaluator or entrypoint — every run asks the contract for its partition and the verifier additionally refuses any checkpoint whose recorded split fingerprint disagrees with the realized one.

Decision: GO. The corpus reproduces its published identity exactly, the partitions are contiguous ranges with no window able to straddle them, no block is a near-duplicate of anything in an earlier partition, and every eval-harness control — including the one built to catch an off-by-one bug — behaves as a correct harness must.

The Journey

Phase 0 — measuring the floor before comparing anything

Five identically-configured runs of the anchor recipe, differing only in seed, give a level: mean 1.56915 nats, standard deviation 0.00802952, range 0.021485. That spread describes how much a single FIT moves — it is provenance, never the bar. The bar a candidate must actually clear is the spread of a comparison: the ten unordered pairs among those same five checkpoints, each pair re-scored on identical validation windows and differenced. That paired spread has standard deviation 0.00747623 and range 0.026494, and the bar is \delta = \max(2\cdot 0.00747623,\ 0.026494/2) = 0.0149525 nats — set from the comparison quantity, not the level quantity, because a keep IS a comparison.

Left panel: the anchor's five seeds as zero-based bars around their mean. Right panel: the ten paired differences that actually set the bar, with the +/-1-floor band shaded.
Phase 0 on the primary track, both panels measured on the development partition: at left the anchor recipe at five seeds as zero-based bars around their mean, at right the ten paired differences between two seeds of the same recipe, with the one-floor band shaded. The bar every later candidate must clear is read off the right panel and not the left — a keep is a comparison, so its floor is measured on comparisons. Close

The anchor

E0001 reruns the exact committed anchor recipe at a sixth seed the floor sweep never used, and scores 1.572174 nats — 0.3766 fit-noise standard deviations from the five-seed mean, comfortably inside the registered bound of two. P1 is supported: the recipe reproduces, and the floor is usable as registered. Two more checks ride along for free. The trainer’s own reported loss and the checker’s independently recomputed loss agree to 0.0 nats, against a declared tolerance of 0.01 — the first of eight runs where that holds. And the same checkpoint, re-scored under KLEIN_DEVICE=cpu and KLEIN_DEVICE=mps, prints 1.572174 both times: a device change moves nothing at the printed resolution. A full re-execution in a detached worktree, same seed, same device, different process, lands 0.000962 nats away — 0.119808 fit-noise standard deviations, because MPS training is not bit-deterministic even when nothing else changes.

Four registered levers, four discards

One idea per transaction, all at the same 2000-step budget, all adjudicated by the notary on the verifier’s printed block — never by prose:

Four levers, four failures to clear the floor, two of them costing multiple floors. That pattern is itself the result that chose the next candidate.

The keep nobody registered

With every registered lever spent, the phase’s free slot went to the reading the first four runs raised: if the binding constraint is optimization progress per step, the cheapest direct test is a schedule change that touches nothing else. E0006, cosine decay from the anchor’s learning rate down to a tenth of it over the same 2000 steps, scores 1.519319 nats — +3.3326 floors better than the anchor, 0.052855 nats in absolute terms. Same parameters, same tokens, same arithmetic per step: only WHEN the learning rate is spent changed. It carried no registered prediction and is the only frontier improvement in the study.

Validation loss against optimizer steps on a log scale, anchor versus cosine decay: the two schedules are indistinguishable for the first few hundred steps and separate once the decay bites.
Development-partition validation loss in nats per character against optimizer steps (log scale) for two single development runs on the primary track — the anchor’s constant learning rate against cosine decay, both retrained from scratch by the registered learning-curve sweep — with a context-free add-one unigram drawn as the dashed reference line. The two schedules are indistinguishable for the first few hundred steps and separate only once the decay bites, so the schedule earns its floors late in the budget rather than early. Close

A referee note on this exact figure: the first render distinguished the two curves by colour alone (same marker, same solid line). Fixed for the version above — the anchor now draws solid with a circle marker, cosine decay dashed with a square marker — so the two stay legible without relying on hue at all. Every value the chart carries was already independently legible from its text annotations, so nothing about the finding changed; the figure is simply easier to read now.

Does warmup’s verdict survive its partner?

A fair objection to E0002: warmup is almost always paired with decay in practice, because a high peak learning rate is only safe if it is later spent down, so testing warmup against a CONSTANT rate may have been an unfair trial. E0007 adds 200 steps of warmup on top of the new E0006 incumbent and scores 1.520867 nats — +3.2291 floors from the anchor but only 0.001548 nats, 0.103528 floors, from the E0006 incumbent it started from: inside the floor, neither cost nor benefit. P2’s registered verdict stands exactly as adjudicated against the anchor, but the honest advice sharpens: decay, and warmup is then optional — not “warmup is harmful.”

All six single-change candidates, in units of the measured floor, against the anchor's five-seed mean. Four fail outright, one sits inside the floor, one clears it.
The six single-change development candidates on the primary track, each as its improvement over the anchor’s five-seed mean on the development partition, measured in units of one measured floor, with the plus-or-minus one-floor band shaded; colour is the effect against the anchor and the bracketed tag is the notary’s frontier decision against the incumbent. Four levers land outside the band in the losing direction, one sits inside it where nothing is decidable, and only the schedule change clears the bar. Close

Six candidate transactions, six single ideas, six notarized verdicts: zero crashes, one keep. The searcher-versus-checker gap stayed at 0.0 nats on every one of them, and the steps/eval_context guardrails held at 2000 and 128 on every run — no candidate bought anything with extra compute.

The full decision trajectory: eight runs in order, the development incumbent as a step line, the one keep as a star, and the sealed final test as a diamond.
The whole decision trajectory of the primary track in run order: every point is the checker’s own recomputed validation loss in nats per character, with the development incumbent as a step line, discards as dots, the single keep as a star, and the once-only sealed final test as the diamond at the right — the only point not measured on the development partition. Development climbs to one keep, and the sealed final tenth then lands above that incumbent, which is the distribution shift a contiguous-block split buys rather than a sign of overfitting. Close

The sealed look

The law requires a dry run before any real sealed access, spending nothing: klein run-one --final-test --dry-run executed the frozen E0006 configuration against development rows and printed confirmation before a single sealed character was ever read. E0008 then retrained the selected cosine-decay recipe on train + development — 111616 more characters than the development incumbent ever saw — and scored it once, on the sealed final tenth: 1.56628 nats, 2.259664 bits per character. That is 5.8485 fit-noise standard deviations from the development incumbent, well outside the registered band of two. P6 is refuted. The sealed run had MORE training data than the incumbent it is compared against, so this is not overfitting; it is 3.140679 measured floors of distribution shift between a contiguous final tenth of a concatenation of plays — different plays, different speakers, different proper nouns — and the rest of the corpus. A contiguous-block split buys leakage safety (the largest cross-partition 8-gram similarity anywhere is 0.030059) and pays for it with exactly this kind of shift, which a shuffled split would have hidden instead of measured.

One track, one sealed access: that arithmetic confirms the selected recipe’s LEVEL on unseen text and nothing else. The 0.052855-nat improvement of cosine decay over the anchor was measured entirely on the development partition, and no sealed measurement of the anchor exists to difference against — so the improvement itself stays exploratory by construction, while the sealed level, 1.56628 nats, is confirmed. The full run-by-run ledger:

Tracks: primary — val_loss (lower is better)

ExpTrackKindMetricStatusDescription
E0001primarydevelopment1.572174keepE0001 identity anchor: the committed anchor recipe at seed 20260903, a seed the Phase-0 floor sweep never used; adjudicates P1; first valid result on this track
E0002primarydevelopment1.584747discardE0002: 200-step linear learning-rate warmup, one change from the anchor at the same 2000 steps and the same seed; adjudicates P2; did not improve track frontier 1.572174 by minimum_delta=0.0149525
E0003primarydevelopment1.739149discardE0003: weight tying — the output head shares the token embedding (1.0% of parameters), one change from the anchor at the same 2000 steps and the same seed; adjudicates P3; did not improve track frontier 1.572174 by minimum_delta=0.0149525
E0004primarydevelopment1.639808discardE0004: dropout 0.1, one change from the anchor at the same 2000 steps and the same seed; adjudicates P4; did not improve track frontier 1.572174 by minimum_delta=0.0149525
E0005primarydevelopment1.57624discardE0005: width 128 to 256 at the same 2000 steps, one change from the anchor with the same seed; adjudicates P5; did not improve track frontier 1.572174 by minimum_delta=0.0149525
E0006primarydevelopment1.519319keepE0006: cosine learning-rate decay from 3e-3 to 10% of it over the same 2000 steps, one change from the anchor with the same seed; no registered prediction, exploratory; frontier improvement over 1.572174 with minimum_delta=0.0149525
E0007primarydevelopment1.520867discardE0007: 200-step linear warmup added to the E0006 cosine incumbent — does warmup pay once it is paired with the decay it is normally used with? No registered prediction, exploratory; did not improve track frontier 1.519319 by minimum_delta=0.0149525
E0008primaryfinal_test1.56628discardsealed confirmation of the selected candidate: the E0006 cosine-decay recipe, retrained on train+development and scored once on the sealed final tenth; adjudicates P6; sealed final-test evidence; excluded from the adaptive frontier

Headroom at the incumbent, against cross-entropy’s true-but-unreachable lower bound of zero, is h = 1.519319 / 0.0149525 \approx 101.609697 floors — “not arithmetically excluded,” and nothing stronger. The detection-limit law does no work in this study; the floor did all of it.

Findings & Insights

Eight notarized runs of a 4-layer character transformer at a fixed 2000-step budget, every checkpoint scored by a verifier the training script could not touch. Four textbook recipe levers were registered as predictions before any of them ran — warmup, weight tying, dropout, width — and not one of them cleared the measured floor; two of them cost multiple floors. The only improvement came from the one lever that carried no prediction at all: when the learning rate is spent. The sealed final tenth then came back 3.140679 measured floors harder than development, so this study confirms a level and not a gap, and says so throughout rather than in a footnote.

Verdicts

ClaimResearch questionVerdictStrength
[C1]RQ1 — the recipe contestsupported, direction reversed: at most one lever cleared the floor, but it was none of the four registered onesexploratory
[C2]RQ2 — checker vs. searchersupported: never a printable disagreement, device-independent, replication inside fit noiseexploratory
[C3]RQ3 — recipes or noise?supported: the largest cost is an order of magnitude past the seed spread, the only gain a small multiple of itexploratory
[C4]RQ1, sealedmeasured: the selected recipe scores 1.56628 nats / 2.259664 bits per character on unseen textconfirmed
[C5]—held: the checker decided every disposition, guardrails held on all eight runs, all four controls behaved correctlyconfirmed
[C6]RQ1, mechanisminterpretation: tying fails because one matrix serves two roles with no logit scale to reconcile them, not because of parameter countexploratory
[C7]RQ1, sealed mechanisminterpretation: the sealed block is a different sample of the corpus's own nonstationarity, not overfittingexploratory

Why so few claims reach confirmed. This track declared exactly one sealed access, and it was spent on the selected candidate. That arithmetic confirms [C4]’s LEVEL and [C5]’s PROCEDURE; every comparison — every floor, every delta, the entire recipe contest — is a development-partition measurement and stays exploratory. One track means one sealed number, and a comparison needs two. Two supported, four refuted, none inconclusive, none open: the method card staked a directional expectation on P2–P5 before they ran and got two of the four right — P2 refuted as expected, P4 supported as expected; P3 was expected supported and was refuted, P5 was marked genuinely uncertain and was refuted.

What defied the prior

The remaining sections turn these claims into what a training-recipe practitioner should actually change, and the entrypoint that produced every number above.

What the records say

The totals below are not typed here: the builder reads them out of this study’s claims.lock and study_state.json, so the claim count, the split by strength and by class, the errata, the lock’s git head, the finalization label and the referee’s verdict are the records themselves rather than a summary of them.

claims
13 locked in claims.lock
by strength
confirmed 2 · exploratory 11
by class
empirical-description 4 · mechanism-interpretation 2 · procedural-verdict 1 · research-discipline 6
errata
0 of 13 claims tagged · 0 erratum record(s) in the lock
locked at
caee71affac9 · klein 2.0.0
label
confirmed
referee
PASS-WITH-NOTES — klein-referee (Claude Code subagent, model: claude-sonnet-5) · independent of the experimenter: yes

Training-recipe advice

The change. Replace a constant learning rate with a cosine decay to a tenth of the peak over the whole budget. The matched-compute condition it held under. 2000 AdamW steps, the same 4-layer 4-head 128-wide causal transformer (824320 parameters), on the same 891904 training characters — every candidate at exactly the same step count, enforced by the checker reading steps out of the checkpoint rather than promised by the training script. The seed spread it was measured against. A paired-comparison bar of 0.0149525 nats. The size of the change. 0.052855 nats, 3.53486 floors — it clears the bar by more than three times, and it is the only one of six single changes that clears it at all. The hardware. Apple silicon, MPS-selected by default; the same checkpoint re-scores identically on CPU. What this does not say. It does not say cosine decay beats a schedule this study never ran, and it does not say the improvement survives to unseen text: the sealed block was 3.140679 floors harder than development for the same recipe, and with one track and one sealed access there is no sealed measurement of the anchor to difference against. Nothing here is priced — this study registers no materiality block, so “improvement” means only that a pre-registered, measured bar was cleared.

Six lessons, each with the run that paid for it

  1. Measure your floor on the quantity your decision actually uses. The five-seed LEVEL spread here has standard deviation 0.00802952; the ten paired DIFFERENCES between two seeds of the same recipe have standard deviation 0.00747623 and range 0.026494, and it is the paired spread a candidate-versus-anchor comparison has to clear. A level spread and a comparison spread are different quantities, and the gap between them is exactly why this contract derives minimum_delta from the second one, never the first.

  2. At a fixed step budget, spend the schedule before you spend the capacity. The only keep in this study was a pure schedule change worth 0.052855 nats, while multiplying the parameter count by 3.908075 was worth -0.4742 floors. A step budget rewards changing WHEN the optimizer moves, not how much it has to move with.

  3. Never let the training script grade its own checkpoint. It costs one extra file: a checker that loads the artifact, asks the contract which rows are the validation set, rebuilds the model from the checkpoint’s own config with its own implementation, and recomputes the loss. Here the two never disagreed by a printable amount against a declared tolerance of 0.01 — the outcome you want, and one you cannot assume without checking.

  4. Put a copy-the-input control in your language-model harness. It bets the next character equals the current one, so a correct harness scores it WORSE than chance — 4.750043 against 4.174388 nats here — while the classic off-by-one target-alignment bug would score it 0.693147. None of this study’s other three controls could have caught that particular bug.

  5. If you split ordered text into contiguous blocks, measure the distribution shift you just bought instead of assuming it away. The identical recipe with MORE training data scored 0.046961 nats worse on the sealed block than on the development block. A contiguous split buys leakage safety; it does not buy identically-distributed partitions, and the honest move is to measure the difference rather than hope it is zero.

  6. Decide at design time how a comparison gets its sealed number. One track and one sealed access can confirm a LEVEL and never a DIFFERENCE. This study’s contract declared one track and said nothing about the gap, so its headline schedule improvement stays exploratory by arithmetic, not by modesty. Either give each family its own track, or pre-register the gap itself as exploratory-by-construction — deciding afterwards is how sealed vocabulary gets stretched.

The entrypoint that produced every number above

The mutable surface this study’s search actually touches is exactly two files. model.py carries the architecture and the CONFIG dict a width or weight-tying candidate edits; verify.py — outside the mutable surface, hashed at the METHOD gate — carries its OWN separate implementation of the same class, so a candidate that changes the module tree produces a checkpoint the checker cannot load, and the run crashes rather than silently comparing two different architectures.

model.py · executed by E0006 (development, track primary) at commit 341279f9f8b8 · sha256 4a16c8f5b171…
"""The architecture half of the mutable surface.

`CONFIG` is what a candidate edits when its one idea is architectural (width,
weight tying, dropout). The class below must keep producing a `state_dict` that
`verify.py`'s own independent copy of the same family can load with
`strict=True` — the checkpoint format IS the contract between the searcher and
the checker, and a candidate that leaves the family produces an artifact the
checker cannot score.

Dropout lives here because it is an architectural switch, but it has no
parameters, so a checkpoint trained with dropout loads into the checker
unchanged and is scored — as it must be — with dropout off.
"""

from __future__ import annotations

import torch
import torch.nn as nn
import torch.nn.functional as F

#: The anchor recipe's architecture. 4 layers x 4 heads x 128 wide over a
#: 128-character context = 824,320 parameters at vocab 65.
CONFIG: dict[str, object] = {
    "vocab_size": 65,
    "n_layer": 4,
    "n_head": 4,
    "n_embd": 128,
    "block_size": 128,
    "tie_weights": False,
    "dropout": 0.0,
}


class Block(nn.Module):
    """Pre-norm transformer block: causal self-attention, then a 4x MLP."""

    def __init__(self, n_embd: int, n_head: int, dropout: float = 0.0) -> None:
        super().__init__()
        self.ln1 = nn.LayerNorm(n_embd)
        self.attn_qkv = nn.Linear(n_embd, 3 * n_embd, bias=False)
        self.attn_proj = nn.Linear(n_embd, n_embd, bias=False)
        self.ln2 = nn.LayerNorm(n_embd)
        self.mlp_fc = nn.Linear(n_embd, 4 * n_embd)
        self.mlp_proj = nn.Linear(4 * n_embd, n_embd)
        self.n_head = n_head
        self.dropout = dropout
        self.attn_drop = nn.Dropout(dropout)
        self.mlp_drop = nn.Dropout(dropout)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        B, T, C = x.shape
        h = self.ln1(x)
        q, k, v = self.attn_qkv(h).split(C, dim=2)
        head_dim = C // self.n_head
        q = q.view(B, T, self.n_head, head_dim).transpose(1, 2)
        k = k.view(B, T, self.n_head, head_dim).transpose(1, 2)
        v = v.view(B, T, self.n_head, head_dim).transpose(1, 2)
        y = F.scaled_dot_product_attention(
            q, k, v, is_causal=True, dropout_p=self.dropout if self.training else 0.0
        )
        y = y.transpose(1, 2).contiguous().view(B, T, C)
        x = x + self.attn_drop(self.attn_proj(y))
        return x + self.mlp_drop(self.mlp_proj(F.gelu(self.mlp_fc(self.ln2(x)))))


class CharTransformer(nn.Module):
    def __init__(
        self,
        *,
        vocab_size: int,
        n_layer: int,
        n_head: int,
        n_embd: int,
        block_size: int,
        tie_weights: bool = False,
        dropout: float = 0.0,
    ) -> None:
        super().__init__()
        self.block_size = block_size
        self.tok_emb = nn.Embedding(vocab_size, n_embd)
        self.pos_emb = nn.Parameter(torch.zeros(1, block_size, n_embd))
        self.drop = nn.Dropout(dropout)
        self.blocks = nn.ModuleList(
            [Block(n_embd, n_head, dropout) for _ in range(n_layer)]
        )
        self.ln_f = nn.LayerNorm(n_embd)
        self.head = nn.Linear(n_embd, vocab_size, bias=False)
        if tie_weights:
            self.head.weight = self.tok_emb.weight

    def forward(self, idx: torch.Tensor) -> torch.Tensor:
        x = self.drop(self.tok_emb(idx) + self.pos_emb[:, : idx.shape[1]])
        for block in self.blocks:
            x = block(x)
        return self.head(self.ln_f(x))


def build(config: dict[str, object] | None = None) -> CharTransformer:
    """Build the model on CPU under whatever torch seed the caller set.

    Building on CPU and moving afterwards is deliberate: it makes the initial
    weights identical on every backend, so a CPU run and an MPS run of the same
    recipe differ only in arithmetic.
    """
    cfg = dict(CONFIG if config is None else config)
    return CharTransformer(
        vocab_size=int(cfg["vocab_size"]),
        n_layer=int(cfg["n_layer"]),
        n_head=int(cfg["n_head"]),
        n_embd=int(cfg["n_embd"]),
        block_size=int(cfg["block_size"]),
        tie_weights=bool(cfg["tie_weights"]),
        dropout=float(cfg["dropout"]),
    )

train.py carries the recipe: everything in the RECIPE dict at the top is the whole per-experiment diff, and everything below it is fixed machinery that a candidate transaction never touches. The version below is the E0006 incumbent — the winning cosine-decay recipe, exactly as committed.

train.py · executed by E0006 (development, track primary) at commit 341279f9f8b8 · sha256 19aa82b459bc…
"""The recipe half of the mutable surface — the whole per-experiment diff.

One candidate = one idea, expressed as `RECIPE` here and/or `CONFIG` in
`model.py`, and nothing else. Everything below the recipe block is fixed
machinery.

What this script does NOT do
----------------------------
It does not decide anything. It trains for exactly `max_steps` optimizer steps,
saves a checkpoint, prints its own honest estimate of the validation loss beside
the `checkpoint:` line, and stops. `klein run-one` then runs `verify.py` as a
separate process, re-derives the loss from the saved checkpoint, and it is THAT
number the disposition uses. This script's number exists only so the two can be
compared: a disagreement beyond 0.01 nats is a crash, and the searcher is not
the one to ask which of them is right.

The validation sweep here is written out independently rather than imported from
`verify.py` on purpose. Two implementations that agree are evidence; one
implementation compared with itself is not.

The partition comes from `kleinlib.data.load_partition`, which prints the
`split_fingerprint:` the notary checks against the DATA gate — and, under
`KLEIN_SEALED_DRYRUN=1`, hands back the development rows and prints
`sealed_dryrun: 1` so the mandatory rehearsal spends no seal.
"""

from __future__ import annotations

import math
import os
import time
from pathlib import Path

import numpy as np
import torch
import torch.nn.functional as F

import model as arch
from kleinlib.data import load_partition, split_fingerprint
from kleinlib.eval import evaluate_scalar
from kleinlib.torch_device import pick_device

# --- the candidate: the whole per-experiment diff surface -------------------
RECIPE: dict[str, object] = {
    "name": "cosine",
    # E0006: ONE change from the anchor — the learning rate decays on a cosine
    # from 3e-3 to 10% of it over the 2000 steps, instead of staying constant.
    # Same parameters, same tokens, same arithmetic per step: only WHEN the
    # learning rate is spent changes. No registered prediction; exploratory.
    "seed": 20260903,
    "max_steps": 2000,      # the BUDGET. The verifier reads it back out of the
                            # checkpoint and the `steps` guardrail pins it.
    "batch_size": 32,
    "lr": 3.0e-3,
    "warmup_steps": 0,
    "schedule": "cosine",   # "constant" | "cosine"
    "lr_final_frac": 0.1,
    "weight_decay": 0.1,
    "beta1": 0.9,
    "beta2": 0.99,
}
# ---------------------------------------------------------------------------

SMOKE = os.environ.get("KLEIN_SMOKE") == "1"
DRY_RUN = os.environ.get("KLEIN_SEALED_DRYRUN") == "1"
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)

#: Windows per forward pass while scoring. Speed only: the loss is a sum over
#: every predicted character and does not depend on the grouping.
SCORE_BATCH = 64
TOKENS_PATH = Path("data/prepared/tokens.bin")
MODELS = Path("models")


def character_range(X, lengths) -> tuple[int, int]:
    """The contiguous character range of a partition of blocks."""
    starts = np.asarray(X["start_char"], dtype=np.int64)
    low = int(starts.min())
    return low, low + int(np.asarray(lengths, dtype=np.int64).sum())


def eval_windows(tokens: np.ndarray, low: int, high: int, context: int):
    """Every full `context`-character window of `[low, high)` — no sampling."""
    n = (high - low - 1) // context
    starts = low + np.arange(n, dtype=np.int64) * context
    x = np.stack([tokens[s : s + context] for s in starts]).astype(np.int64)
    y = np.stack([tokens[s + 1 : s + 1 + context] for s in starts]).astype(np.int64)
    return x, y


def validation_loss(net, device, x: np.ndarray, y: np.ndarray) -> float:
    net.eval()
    total, count = 0.0, 0
    with torch.no_grad():
        for i in range(0, len(x), SCORE_BATCH):
            logits = net(torch.from_numpy(x[i : i + SCORE_BATCH]).to(device))
            target = torch.from_numpy(y[i : i + SCORE_BATCH]).to(device)
            total += float(
                F.cross_entropy(
                    logits.reshape(-1, logits.shape[-1]),
                    target.reshape(-1),
                    reduction="sum",
                )
            )
            count += int(target.numel())
    net.train()
    return total / count


def main() -> None:
    t0 = time.time()
    evaluation_kind = os.environ.get("KLEIN_EVALUATION_KIND")
    if SMOKE:
        evaluation_kind = evaluation_kind or "development"
    missing = [
        name
        for name, value in (
            ("KLEIN_EVALUATION_KIND", evaluation_kind),
            ("KLEIN_EXPERIMENT_ID", EXPERIMENT_ID),
            ("KLEIN_TRACK", TRACK),
        )
        if value is None
    ]
    if missing:
        raise RuntimeError(
            "train.py must be invoked through `klein run-one`. For a pre-run "
            "syntax/shape check use `KLEIN_SMOKE=1 python train.py` — it prints "
            "the canonical block, writes no evidence, and is not evidence. "
            "Missing: " + ", ".join(missing)
        )

    X_fit, X_eval, y_fit, y_eval = load_partition(evaluation_kind, study_dir=".")
    # Under the sealed rehearsal `load_partition` hands back DEVELOPMENT rows;
    # the checkpoint must say what it was actually scored on, not what was asked.
    scored_kind = "development" if DRY_RUN else evaluation_kind
    fingerprint = split_fingerprint(X_fit, X_eval)

    tokens = np.fromfile(TOKENS_PATH, dtype=np.uint8)
    fit_low, fit_high = character_range(X_fit, y_fit)
    eval_low, eval_high = character_range(X_eval, y_eval)

    config = dict(arch.CONFIG)
    context = int(config["block_size"])
    seed = int(RECIPE["seed"])
    steps = 20 if SMOKE else int(RECIPE["max_steps"])
    batch = int(RECIPE["batch_size"])
    lr = float(RECIPE["lr"])
    warmup = int(RECIPE["warmup_steps"])
    schedule = str(RECIPE.get("schedule", "constant"))
    final_frac = float(RECIPE.get("lr_final_frac", 1.0))

    device = pick_device()
    torch.manual_seed(seed)
    net = arch.build(config).to(device)
    optimizer = torch.optim.AdamW(
        net.parameters(),
        lr=lr,
        betas=(float(RECIPE["beta1"]), float(RECIPE["beta2"])),
        weight_decay=float(RECIPE["weight_decay"]),
    )

    rng = np.random.default_rng(seed)
    span = fit_high - fit_low - context - 1
    fit_start = time.time()
    net.train()
    last_loss = float("nan")
    for step in range(steps):
        if warmup > 0 and step < warmup:
            scale = (step + 1) / warmup
        elif schedule == "cosine":
            progress = (step - warmup) / max(1, steps - warmup)
            scale = final_frac + (1.0 - final_frac) * 0.5 * (1.0 + math.cos(math.pi * progress))
        else:
            scale = 1.0
        for group in optimizer.param_groups:
            group["lr"] = lr * scale
        # Streamed index-shuffle batching (war story 2): no DataLoader, no
        # TensorDataset — offsets drawn straight from the token array.
        offsets = fit_low + rng.integers(0, span, size=batch)
        xb = np.stack([tokens[s : s + context] for s in offsets]).astype(np.int64)
        yb = np.stack([tokens[s + 1 : s + 1 + context] for s in offsets]).astype(np.int64)
        logits = net(torch.from_numpy(xb).to(device))
        loss = F.cross_entropy(
            logits.reshape(-1, logits.shape[-1]),
            torch.from_numpy(yb).to(device).reshape(-1),
        )
        optimizer.zero_grad(set_to_none=True)
        loss.backward()
        optimizer.step()
        last_loss = float(loss.detach())
    fit_seconds = time.time() - fit_start

    x_eval, y_eval_windows = eval_windows(tokens, eval_low, eval_high, context)
    reported = validation_loss(net, device, x_eval, y_eval_windows)

    MODELS.mkdir(parents=True, exist_ok=True)
    checkpoint_path = MODELS / f"{EXPERIMENT_ID}.pt"
    torch.save(
        {
            "config": config,
            "state_dict": {k: v.detach().cpu() for k, v in net.state_dict().items()},
            "steps": steps,
            "evaluation_kind": scored_kind,
            "split_fingerprint": fingerprint,
            "reported_val_loss": reported,
            "recipe": str(RECIPE["name"]),
            "seed": seed,
            "lr": lr,
            "batch_size": batch,
            "warmup_steps": warmup,
            "schedule": schedule,
            "lr_final_frac": final_frac,
        },
        checkpoint_path,
    )
    posix = checkpoint_path.as_posix()
    # `checkpoint:` is what `tracks.primary.verifier.artifact_key` names;
    # `artifact:` is what the notary hashes into the manifest. Same file.
    print(f"checkpoint: {posix}")
    print(f"artifact: {posix}")

    evaluate_scalar(
        reported,
        exp_id=EXPERIMENT_ID,
        metric_name="val_loss",
        metric_goal="lower",
        extra={
            "train_steps": str(steps),
            "fit_seconds": f"{fit_seconds:.3f}",
            "train_chars": str(fit_high - fit_low),
            "eval_chars": str(eval_high - eval_low),
            "eval_windows": str(len(x_eval)),
            "final_train_batch_loss": f"{last_loss:.6f}",
            "train_bpc": f"{reported / math.log(2):.6f}",
            "recipe_warmup_steps": str(warmup),
            "recipe_cosine": str(int(schedule == "cosine")),
            "recipe_lr_final_frac": f"{final_frac:.4f}",
            "recipe_lr": f"{lr:.6g}",
            "recipe_dropout": f"{float(config['dropout']):.4f}",
            "recipe_n_embd": str(int(config["n_embd"])),
            "recipe_tie_weights": str(int(bool(config["tie_weights"]))),
            "recipe_seed": str(seed),
        },
        study_dir=".",
        t0=t0,
    )


if __name__ == "__main__":
    main()

Three details in that file are worth reading deliberately rather than skimming past. The batching is a streamed index shuffle straight out of a numpy array — no DataLoader, no TensorDataset — because on Apple-silicon MPS that combination has silently collapsed predictions to a constant in earlier work in this repository; drawing offsets directly from the token array sidesteps the failure mode entirely rather than working around it after the fact. The model is built on CPU and moved to the device afterward (arch.build(config).to(device)), which is deliberate and easy to delete by accident: it is what makes a CPU run and an MPS run of the same seed start from identical weights, and is the reason the device-agreement check in the journey section above is a meaningful comparison rather than a coincidence. The partition never comes from a literal seed or a hardcoded split — every run asks kleinlib.data.load_partition, which prints the realized split_fingerprint back for the notary to compare against the one frozen at the DATA gate. A study elsewhere in this repository once hardcoded a retired split seed directly into an evaluator and silently scored the wrong partition for an entire ledger lane; the fingerprint check exists specifically so that failure mode is caught by the notary before a single number is trusted, not discovered later by a numeral that happens to look wrong.

Next Steps

  1. A second schedule setting, since the schedule is the only lever that paid. Cosine to zero rather than to a tenth of the peak, and a higher peak paid for by the decay. This is the cheapest test of whether E0006 found the lever itself or merely one point on it.

  2. Weight tying WITH a learned logit scale. [C6] blames the shared-norm constraint rather than the parameter sharing itself; a single scalar multiplying the tied logits separates those two explanations in one run.

  3. Width at matched FLOPs instead of matched steps — the wider model with proportionally fewer steps, the scaling-law condition this study deliberately did not run. It converts “capacity does not pay at fixed steps” into a statement about where the exchange rate actually sits.

  4. A two-track version of this study, one track per schedule family, so the gap between them gets two sealed numbers instead of one. [C13] is the reason, and it is the cheapest way to turn this study’s exploratory headline into a confirmed one.

Verified references

Every entry below was checked against its arXiv, publisher or repository page on 2026-09-03; none is unverified.

This is the first Klein study to close under the ml-research profile, and its literature scorecard is the first entry in knowledge/domains/ml-research/: of two uninformed priors, RQ1’s was half right (at most one lever cleared the floor, but not the one it named) and RQ3’s was right in magnitude for the gain and wrong for the largest cost. The next study in this profile is the one with a knowledge base to start from.