"I implemented GPT-2" can mean three very different things. You can load OpenAI's weights into your own code and show it computes the same function. You can make the training loop fast. Or you can start from random weights and train a model that actually learns something. All three happened in my repository neuron-to-gpt, my weekly submissions for a 12-week AI program that went from a single neuron to GPT-2. Keeping their numbers apart turned out to be harder than producing them.

The GPT-2 weeks follow the outline of Andrej Karpathy's "Let's reproduce GPT-2 (124M)" lecture, so the model itself will look familiar. This post is about what I added around it: a full-logit parity test on English, Turkish and emoji prompts that guards the weight import, a speed ladder where every stage is timed on its own and the flash stage cannot silently fall back, a resumable training run with its interruption written into the record, and a paired comparison against GPT-2 on a held-out HellaSwag cohort.

TL;DR

Stage What it is Headline number What it proves
Week 10 My GPT-2 holding OpenAI's weights max logit diff 5.3e-05 to 8.4e-05 on an A100 (rtol = atol = 1e-4 per logit) my code computes the reference function
Week 11 Cumulative speed stages on an L4 53.75 → 36.23 ms per update, 1.48× which change actually helped, at one small shape
Week 12 Random init, 60 min on an NVIDIA L4 validation NLL 11.01 → 4.98; HellaSwag 27.6% my training pipeline learns
G4 That checkpoint, 90 more minutes on an RTX PRO 6000 NLL 4.98 → 3.67; HellaSwag 27.6% → 32.3% on the first 1,000 examples, 30.5% vs GPT-2's 33.7% on a held-out 1,000 real progress; below GPT-2 on both cohorts' point estimates

Validation loss across the L4 run and the G4 continuation

The model

Standard GPT-2 small: 12 blocks, 12 heads, width 768, 1,024 positions, pre-LayerNorm, tanh-approximate GELU, learned absolute positions and a fused Q/K/V projection. The token embedding and the output layer share one matrix (weight tying), which saves 50,257 × 768 = 38,597,376 parameters: the tied model has 124,439,808 unique parameters, the untied one would have 163,037,184.

Initialization follows GPT-2: std 0.02 for weight matrices, and std 0.02/√(2L) for the two residual output projections in each block. Every block adds two contributions to the residual stream, so without the smaller scale the variance of the stream grows with depth.

Week 10: weight parity is a correctness test, not training

To check the implementation, I import the published OpenAI weights (the Hugging Face copy, pinned to a fixed revision) into my own modules and compare outputs.

The trap is in the import. Hugging Face's GPT-2 uses a historical Conv1D layer that stores weights as (input, output). nn.Linear expects (output, input). So four weight matrices per block must be transposed. For three of them a forgotten transpose fails loudly with a shape error. The attention output projection is 768 × 768, so a missing transpose there loads without complaint and silently computes a different function.

From load_hf_weights in week10/model.py:

transposed_suffixes = ( ".attn.c_attn.weight", ".attn.c_proj.weight", ".mlp.c_fc.weight", ".mlp.c_proj.weight", ) ... tensor = source[name].t() if name.endswith(transposed_suffixes) else source[name] destination.copy_(tensor) 

The loader validates every key and every shape before copying anything, so a late mismatch cannot leave a half-loaded model behind.

The parity check compares full logits, not a sample. Both models get the same input in FP32, with eager attention, TF32 off and dropout off, and every logit must agree within rtol = atol = 1e-4. I used three prompts on purpose: an English sentence, a Turkish one, and a mixed string with an emoji, so that multi-byte BPE paths are exercised too. On an A100 the largest absolute difference per prompt was between 5.3e-05 and 8.4e-05, and all three passed; the same check also passed on a T4.

That proves my code computes the same function as the reference when it holds the same weights. It says nothing about whether my code can learn. For that, Week 10 has a deliberately narrow diagnostic: 300 updates on one fixed batch (4 × 32 tokens) from random weights. Loss went from 11.056 to about 0.0001 and token accuracy reached 100%. That is memorization of a single batch. It shows gradients flow and the optimizer steps; it is not evidence of generalization, and I never report it as such.

Week 11: a speed ladder where every rung is measured

The question for Week 11 was simple: which of the usual speed-ups actually helps on the GPU I have? Instead of switching everything on at once, each stage is added on top of the previous one and timed separately.

Week 11 speed stages on an NVIDIA L4

Stage (cumulative) Median ms / update Tokens/s vs previous
baseline, FP32, eager attention 53.750 4,762.8 1.000×
+ TF32 matmul 53.043 4,826.3 1.013×
+ BF16 autocast 59.097 4,331.9 0.898×
+ torch.compile 36.790 6,958.4 1.606×
+ SDPA, flash kernel only 36.171 7,077.4 1.017×
+ vocabulary padded to 50,304 36.227 7,066.6 0.998×

The conditions matter as much as the numbers: B = 2, T = 128, 5 warmup updates, 20 timed updates per stage, one run, on an NVIDIA L4. Each timed update includes data transfer, forward, backward, unscale/clip and the AdamW step, with a CUDA synchronization per step. Compile time and warmup are excluded (compilation plus warmup took about 42 seconds for that stage).

What I took from it:

  • The torch.compile stage was the largest single step: 1.606× on top of the TF32 and BF16 stages. The whole ladder came to 1.48× against the FP32 baseline. Compile was not measured in isolation, so part of that step may simply be recovering what the BF16 stage lost.
  • BF16 autocast made things slower here (0.898×). I did not profile why. At B = 2, T = 128 the step is small enough that overheads can outweigh faster math, but that is a hypothesis, not a measurement. Either way it is a fact about this shape on an L4, not about mixed precision in general, and it is exactly the kind of result that disappears if you only compare "everything on" with "everything off".
  • No fake FlashAttention. The flash stage runs inside sdpa_kernel(SDPBackend.FLASH_ATTENTION), which disallows the math and memory-efficient fallbacks. If the flash kernel cannot run, the stage fails instead of quietly measuring something else under the flash label.
  • Vocabulary padding showed no measurable gain in this single run (0.998×). Padding 50,257 to 50,304 (a multiple of 64) is a common trick; I would need repeated runs to say more. The padded model has 124,475,904 parameters, and the 47 extra classes are implementation-only: they are excluded from sampling and from evaluation.

Gradient accumulation also gets a correctness rule: K micro-batches with equal token counts each contribute loss / K, so the summed gradient equals the gradient of the mean loss over the combined batch. Clipping and the AdamW step happen once per update, after unscaling.

Week 12: a real dataset, from random weights

Week 12 is a separate model. It starts from random weights, not from OpenAI's.

Data pipeline

  • Source: FineWeb-Edu sample-10BT, pinned to a fixed dataset revision, so the run can be traced back to exact documents.
  • Split by document, not by token. Validation documents are filled first and never appear in training; exact duplicates are removed. Near-duplicate cleaning and benchmark contamination scans were not done, and the report says so.
  • Budget in tokens, not documents: 20,000,000 training tokens in 20 shards and a 131,072-token validation shard, all counted with the GPT-2 tokenizer, with an end-of-text token at each document boundary.
  • Storage: 1M-token uint16 NPY shards, each with a SHA-256 in the manifest. The loader memory-maps the shards and builds windows that cross shard boundaries, so no tail of a shard is silently dropped.
  • Fixed validation: every check measures exactly the same first 32 batches = 32,768 target tokens. A validation number that moves because the slice moved is worthless.

Training setup

B = 4, T = 256, accumulation 4 (4,096 tokens per update), BF16, SDPA, torch.compile, a 100-update warmup and a 60-minute wall-clock budget. The checkpoint (last.pt) stores not just weights but the AdamW and scaler state, the data loader position and the RNG state, so a Colab disconnect does not silently restart the data stream or the schedule.

The run made 19,586 updates and processed 80,224,256 tokens in 60.20 minutes. Validation NLL went from 11.013 to 4.984965.

HellaSwag, done carefully

HellaSwag gives a context and four endings; the model picks the ending it finds most likely. Small protocol choices move the score by points, so I pinned all of them:

  • Dataset: the deprecated GitHub JSONL URL now returns 404, so I use Rowan/hellaswag from the Hugging Face Hub, pinned to a revision.
  • Scoring: only the ending tokens are scored, using mean token NLL (acc_norm). The context is encoded once, each ending is encoded separately with its leading space, and nothing is cleaned up.
  • Long contexts are left-trimmed by the same amount for all four endings, so no ending gets an advantage from extra context.
  • Same vocabulary for both models: logits are sliced to the 50,257 real GPT-2 IDs, removing my model's 47 padding classes before the softmax.
  • Same numerics: FP32, TF32 off, for my model and for OpenAI GPT-2 (weights pinned to a revision and loaded into my own implementation).
losses = F.cross_entropy( logits[..., :50257].float().reshape(-1, min(50257, logits.shape[-1])), targets.reshape(-1), reduction="none").reshape_as(targets) totals = (losses * mask).sum(-1) # mask: ending positions only means = totals / mask.sum(-1) # acc_norm uses the mean 

On the first 1,000 validation examples, my 60-minute model scored 27.6% (chance is 25%). OpenAI GPT-2, under the identical protocol, scored 33.6%. Eighty million tokens is a small experiment, not a pretraining reproduction; a gap is expected, though this run does not isolate its causes.

A note on the absolute numbers. Karpathy's build-nanogpt script, with the same completion-style acc_norm, reports 29.55% for GPT-2 124M on all 10,042 validation examples. My 1,000-example slices give GPT-2 33.6% and 33.7%, and the Wilson interval for 33.6% (about 30.7% to 36.6%) does not reach 29.55%. So the first 2,000 examples of the pinned Rowan/hellaswag split look easier than the full set, or something in the data source differs; I did not run the full set to find out. The scores in this post are therefore comparable with each other, under one protocol and on the same indices, and not with published full-set numbers.

G4: continuing my own checkpoint on a bigger GPU

The last experiment takes that exact L4 checkpoint, verifies its hash, and continues training on an NVIDIA RTX PRO 6000 Blackwell GPU for 90 minutes. It is not started from OpenAI weights.

Settings: B = 8, T = 1,024, accumulation 4 (32,768 tokens per update), BF16, SDPA, torch.compile and fused AdamW with β = (0.9, 0.95), ε = 1e-8, weight decay 0.1 on matrices and gradient clipping at 1.0. The learning rate warms up over 30 successful updates and then follows a cosine envelope tied to wall-clock time, from 3e-4 down to 3e-5, so the schedule ends when the budget ends regardless of throughput.

Fresh data, checked against the old run. A new 200M-token training pool was drawn from the same pinned FineWeb-Edu revision. Every document whose SHA-256 exactly matches a document in the earlier L4 training or validation set was removed. The 131,072-token validation shard was carried over byte for byte, so the L4 and G4 validation numbers measure the same 32,768 targets.

Resume bookkeeping is part of the result. The first session was planned against a clock deadline. It was interrupted after 3,989 committed updates and resumed from the verified checkpoint; on resume the deadline-based limit was removed and the total budget across both sessions set to 90 minutes (the pause between sessions is not counted). The 3,989 updates were kept and 16,384 tokens from an unfinished micro-batch were read again. The source version, the old and new budget settings and the checkpoint hash are all recorded under resumes in training.json. A loss curve without its resume history is hard to trust.

Result: 38,061 updates, 1,247,182,848 processed tokens, 90.01 minutes, about 230,933 tokens/s over wall time. Validation NLL fell from 4.984965 to 3.665616.

Two caveats travel with those numbers. Processed tokens are not unique data: the 200M-token pool was seen about 6.24 times. And the throughput is not a controlled comparison with the L4 run, because context length, batch, data and hardware all changed.

Two HellaSwag cohorts, chosen before looking

HellaSwag accuracy with Wilson intervals

Evaluation L4 checkpoint G4 continuation OpenAI GPT-2
FineWeb validation NLL (fixed 32,768 targets) 4.984965 3.665616 not measured
HellaSwag, indices 0–999 27.6% 32.3% 33.6%
HellaSwag, indices 1,000–1,999 not measured 30.5% 33.7%

Indices 0–999 were already used in Week 12, so they only show continuity: the same examples went from 27.6% to 32.3%. Indices 1,000–1,999 were reserved in advance as the main comparison, and the checkpoint was selected by validation loss, never by HellaSwag. On that held-out cohort my model scores 30.5% and GPT-2 33.7%.

Both models answer the same questions, so I compare them pairwise instead of treating the two accuracies as independent:

Cohort Only mine correct Only GPT-2 correct Paired bootstrap 95% CI (mine − GPT-2) Exact McNemar p
0–999 88 101 [−4.00, +1.40] points 0.383
1,000–1,999 58 90 [−5.60, −0.80] points 0.0106

The bootstrap uses 20,000 resamples with seed 20261108 and assumes independent examples, so it is a rough uncertainty measure. Read plainly: on the first cohort the data cannot separate the two models; on the held-out cohort GPT-2 is ahead. There is no equivalence claim to make, and nothing here says anything about chat, code or reasoning.

What the text looks like

Same prompt, seed 42, temperature 0.8, top-k 50, at most 48 new tokens. At the start of G4:

The children walked into the way, which is called the "Kak," they take into account their own needs and can be taught in the form of "Rarm," ...

At the end of G4:

The children walked into the school and enjoyed the music. As the summer started to get underway, the teacher was amazed at the new songs. A young man was still amazed by the songs. ...

The sentences are better formed, but the model still repeats itself and loses the thread a few lines later. One sample is an illustration, not an evaluation.

Lessons I would apply to any training project

  1. Compare full logits, not shapes. A missing transpose on the square attention projection passes a shape check. Include non-ASCII text so multi-byte BPE paths are exercised too.
  2. Measure optimizations one at a time. The ladder showed BF16 slowing things down at a small shape and the torch.compile stage as the largest single step (1.606× on top of TF32 and BF16). An all-on versus all-off comparison would have hidden both.
  3. Make silent fallbacks impossible. If the flash kernel is not allowed to fall back, a flash number really is a flash number.
  4. Pin everything that can drift. Dataset revision, model revision, the validation slice, the HellaSwag source, the scoring code. Otherwise a later number is not comparable to an earlier one.
  5. Choose the held-out set before you look. It is the reason I treat 30.5% as the result and 32.3% as continuity.
  6. Keep claims apart in the repository, not only in the prose. Week 10 imports weights to verify code; Week 12 starts from random; G4 continues Week 12; OpenAI GPT-2 is only an evaluation reference.

Limits

  • Week 12 and G4 are single runs. I did not measure seed-to-seed variance.
  • G4 processed 1.25B tokens but only 200M unique ones (about 6.24 passes), so its token count overstates the data it saw. I did not compare against a no-repeat run.
  • HellaSwag was run on two 1,000-example slices, not on the full 10,042-example set.
  • GPU inference was not rerun locally. I verified the exported file hashes, the token and update accounting, and the predictions reconstructed from the saved per-example NLL scores.
  • Rerunning G4 needs my backed-up checkpoint and token shards. A fresh clone contains the evidence, not the weights.
  • G4 run environment: PyTorch 2.14.1+cu130, CUDA 13.0, Python 3.13.16. Requirements use version ranges, not a lockfile.
  • This is a base language model study, not a chat assistant or a production service.

The evidence check runs without a GPU, a checkpoint or a dataset download:

git clone https://github.com/muend/neuron-to-gpt cd neuron-to-gpt python experiments/g4/analyze_results.py --check 

The check recomputes file hashes, token and update accounting, and the correct counts from the saved per-example NLL scores; it does not rerun the model. The G4 report and its per-example evaluation files are in experiments/g4/results/nvidia_rtx_pro6000/, the speed ladder in week11/results/nvidia_l4/, and the parity report in week10/results/. The Week 12 README lists build-nanogpt's HellaSwag script as the reference evaluation protocol.

If you spot a flaw in the evaluation setup, I would like to hear about it in the comments.