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:
- 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).
- 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).
- 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# | Lever | Rule on the verifier's printed block |
|---|---|---|
| P1 | the anchor recipe at a seed the floor sweep never used | anchor_z <= 2 |
| P2 | linear learning-rate warmup | delta_in_floors >= 1 |
| P3 | weight tying (output head shares the token embedding) | abs(delta_in_floors) < 1 |
| P4 | dropout 0.1 | delta_in_floors <= -1 |
| P5 | width 128 → 256 | delta_in_floors >= 1 |
| P6 | the sealed final tenth of the corpus | abs(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.
where is the complete, non-overlapping tiling of the evaluation range into windows of characters — no sampling, no seed. A model that has learned nothing scores a uniform 4.174387 nats (); 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 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:
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:
Every registered prediction below is written as an integer count of , fixed before itself was known.
Three deliberate design choices, and what each costs
- 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. - 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.
- 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.
| Partition | Blocks | Characters | Share |
|---|---|---|---|
| train | 871 | 891904 | 79.96% |
| development | 109 | 111616 | 10.01% |
| sealed final test | 109 | 111874 | 10.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 partition | Compared against | Max Jaccard |
|---|---|---|
| development | train | 0.023131 |
| sealed | train + development | 0.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:
| Control | Role | Score (nats/char) | Verdict |
|---|---|---|---|
| uniform | negative — chance | 4.174388 | PASS |
| untrained network | negative — no information | 4.305432 | PASS |
| add-one unigram | positive — real information | 3.306991 | PASS |
| copy-the-input | negative — off-by-one detector | 4.750043 | PASS |
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 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 nats — set from the comparison quantity, not the level quantity, because a keep IS a comparison.
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:
- E0002, linear warmup on a constant learning rate — 1.584747 nats, floors. P2 refuted, and refuted on the wrong side of “no effect”: warmup did not merely fail to help, it cost more than a full floor. The steps spent ramping up to the target rate are steps not spent learning, and a fixed budget never gives them back.
- E0003, weight tying — 1.739149 nats, floors, 21.1718 fit-noise standard deviations from the anchor. P3 refuted by an order of magnitude, in the losing direction — the single largest effect measured anywhere in this study. Tying removes 8320 of 824320 parameters, 1.009317 percent, which is why the method card expected it to be invisible; forcing one matrix to be both the input lookup and the output classifier, with no logit scale to reconcile the two roles’ very different norms, was not invisible at all.
- E0004, dropout 0.1 — 1.639808 nats, floors. P4 supported — the card’s least safe prior, because enough passes over the train partition can make a model regularization-limited, and dropout would then pay. It did not: at this budget the binding constraint is optimization, not generalization, and making every step noisier is a straight loss.
- E0005, width 128 → 256 — 1.576240 nats, floors, on a model with 3.908075 times the anchor’s parameters. P5 refuted — inside the floor, in the wrong direction. A wider model gets the same number of gradient updates as a narrower one at a fixed STEP budget, and simply has more parameters to move with each of them; this is not the compute-optimal regime scaling-law doctrine describes, and the honest statement is that capacity was not the binding constraint here.
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 — 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.
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 — 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.”
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 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)
| Exp | Track | Kind | Metric | Status | Description |
|---|---|---|---|---|---|
| E0001 | primary | development | 1.572174 | keep | E0001 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 |
| E0002 | primary | development | 1.584747 | discard | E0002: 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 |
| E0003 | primary | development | 1.739149 | discard | E0003: 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 |
| E0004 | primary | development | 1.639808 | discard | E0004: 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 |
| E0005 | primary | development | 1.57624 | discard | E0005: 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 |
| E0006 | primary | development | 1.519319 | keep | E0006: 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 |
| E0007 | primary | development | 1.520867 | discard | E0007: 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 |
| E0008 | primary | final_test | 1.56628 | discard | sealed 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 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
| Claim | Research question | Verdict | Strength |
|---|---|---|---|
| [C1] | RQ1 — the recipe contest | supported, direction reversed: at most one lever cleared the floor, but it was none of the four registered ones | exploratory |
| [C2] | RQ2 — checker vs. searcher | supported: never a printable disagreement, device-independent, replication inside fit noise | exploratory |
| [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 it | exploratory |
| [C4] | RQ1, sealed | measured: the selected recipe scores 1.56628 nats / 2.259664 bits per character on unseen text | confirmed |
| [C5] | — | held: the checker decided every disposition, guardrails held on all eight runs, all four controls behaved correctly | confirmed |
| [C6] | RQ1, mechanism | interpretation: tying fails because one matrix serves two roles with no logit scale to reconcile them, not because of parameter count | exploratory |
| [C7] | RQ1, sealed mechanism | interpretation: the sealed block is a different sample of the corpus's own nonstationarity, not overfitting | exploratory |
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
- Weight tying was the single most expensive thing this study did. The method card’s parameter arithmetic — 8320 of 824320 parameters, 1.009317 percent — predicted an invisible change. It cost 21.1718 fit-noise standard deviations, the largest effect measured anywhere here, because the parameter COUNT was the wrong quantity to reason about: at a 65-row vocabulary seen constantly, forcing one matrix to be both the input lookup and the output classifier removed a degree of freedom the model was actually using.
- Width bought nothing at a fixed step budget. 3.908075 times the parameters moved the loss in the wrong direction, inside the floor. Holding STEPS fixed is a harsher condition than holding FLOPs fixed, and it is the condition a practitioner with a wall-clock deadline and a fixed dataset actually faces — not a contradiction of scaling-law doctrine, but its honest boundary.
- The only thing that worked carried no prediction. Four registered levers, four failures; the keep came from the phase slate’s fifth candidate, which nobody had staked a registered claim on. That asymmetry is a finding about which levers the literature discusses most, not about the machinery.
- Warmup’s verdict depended on its partner. Against a constant learning rate it cost -1.0431 floors; against the cosine schedule it normally travels with, it landed at 0.103528 floors from the incumbent — inside the floor, neither cost nor benefit. A lever tested against the wrong partner answers a different question than the one it was meant to answer.
- The sealed tenth was harder, and it was not overfitting. The sealed run trained on 111616 MORE characters than the development incumbent and still scored worse — a distribution-shift bill for the leakage protection a contiguous split buys, not a symptom of memorization (the largest cross-partition similarity found anywhere was 0.030059).
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
13locked inclaims.lock- by strength
- confirmed
2· exploratory11 - by class
- empirical-description
4· mechanism-interpretation2· procedural-verdict1· research-discipline6 - errata
0of13claims tagged ·0erratum record(s) in the lock- locked at
caee71affac9· klein2.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
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_deltafrom the second one, never the first.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.
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.
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.
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.
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
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.
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.
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.
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.
- Vaswani, A.; Shazeer, N.; Parmar, N.; Uszkoreit, J.; Jones, L.; Gomez, A. N.; Kaiser, L.; Polosukhin, I. (2017). Attention Is All You Need. Advances in Neural Information Processing Systems 30. arXiv:1706.03762 — the architecture family this study fixes: causal multi-head self-attention with a position-wise MLP.
- Loshchilov, I. & Hutter, F. (2019). Decoupled Weight Decay Regularization. ICLR 2019. arXiv:1711.05101 — the anchor recipe’s optimizer, AdamW, and why weight decay is decoupled from the loss gradient.
- Xiong, R.; Yang, Y.; He, D.; Zheng, K.; Zheng, S.; Xing, C.; Zhang, H.; Lan, Y.; Wang, L.; Liu, T.-Y. (2020). On Layer Normalization in the Transformer Architecture. ICML 2020. arXiv:2002.04745 — why P2’s prior expected warmup not to pay: Pre-LN transformers have well-behaved gradients at initialization.
- Press, O. & Wolf, L. (2017). Using the Output Embedding to Improve Language Models. EACL 2017. arXiv:1608.05859 — the weight-tying result P3 tested, measured originally at word-level vocabularies of tens of thousands.
- Srivastava, N.; Hinton, G.; Krizhevsky, A.; Sutskever, I.; Salakhutdinov, R. (2014). Dropout: A Simple Way to Prevent Neural Networks from Overfitting. Journal of Machine Learning Research 15(56), 1929-1958 — the regularizer P4 tested, and the trade it bets against: dropout buys generalization by slowing optimization.
- Kaplan, J.; McCandlish, S.; Henighan, T.; Brown, T. B.; Chess, B.; Child, R.; Gray, S.; Radford, A.; Wu, J.; Amodei, D. (2020). Scaling Laws for Neural Language Models. arXiv:2001.08361 — the doctrine anchor behind P5: at fixed COMPUTE, larger models trained for fewer steps are efficient. This study holds steps fixed instead of FLOPs, a different and harsher condition for the wider model.
- Hoffmann, J.; Borgeaud, S.; Mensch, A.; et al. (2022). Training Compute-Optimal Large Language Models. arXiv:2203.15556 — the correction that matters here: model size and training tokens should scale together, so a width change at fixed tokens is deliberately off the compute-optimal frontier.
- Picard, D. (2021).
Torch.manual_seed(3407)is all you need. arXiv:2109.08203 — why this study measures a seed floor before it compares anything: seed-to-seed spread produces outliers large enough to be mistaken for a method effect. - Bouthillier, X.; Delaunay, P.; Bronzi, M.; Trofimov, A.; Nichyporuk, B.; Szeto, J.; Mohammadi Sepahvand, N.; Raff, E.; Madan, K.; Voleti, V.; Ebrahimi Kahou, S.; Michalski, V.; Arbel, T.; Pal, C.; Varoquaux, G.; Vincent, P. (2021). Accounting for Variance in Machine Learning Benchmarks. MLSys 2021. arXiv:2103.03098 — the methodological anchor for the floor design: benchmark variance has several distinct sources, and which one you measure decides which differences you can honestly call real.
- Karpathy, A. nanoGPT — “The simplest, fastest repository for
training/finetuning medium-sized GPTs”. github.com/karpathy/nanoGPT, MIT license
— the lineage of this exact setting: nanoGPT’s
shakespeare_charexample reads the same tiny-Shakespeare file this study bundles, with the same contiguous 90/10 convention. Cited for provenance of the corpus and the split convention, not for any number.
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.