{"slug": "building-gpt-2-124m-in-pytorch-weight-parity-a-speed-ladder-and-about-150-gpu-of", "title": "Building GPT-2 (124M) in PyTorch: weight parity, a speed ladder and about 150 GPU-minutes of my own training", "summary": "A developer built a from-scratch PyTorch implementation of GPT-2 (124M) in a repository called neuron-to-gpt, validating it against OpenAI's published weights with a full-logit parity test that passed on English, Turkish and emoji prompts with a maximum logit difference of 5.3e-05 to 8.4e-05 on an A100. The work also includes a timed speed ladder on an L4 (53.75 to 36.23 ms per update, 1.48x) and a resumable training run from random initialization that reached validation NLL 3.67 and 32.3% HellaSwag on the first 1,000 examples, versus GPT-2's 33.7% on a held-out 1,000. The developer notes the checkpoint remains below GPT-2 on both cohorts' point estimates.", "body_md": "\"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](https://github.com/muend/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.\n\nThe 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.\n\n**TL;DR**\n\n| Stage | What it is | Headline number | What it proves | \n|---|---|---|---|\n| 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 | \n| 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 | \n| Week 12 | Random init, 60 min on an NVIDIA L4 | validation NLL 11.01 → 4.98; HellaSwag 27.6% | my training pipeline learns | \n| 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 | \n\nStandard 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.\n\nInitialization 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.\n\nTo 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.\n\n**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.\n\nFrom `load_hf_weights` in `week10/model.py`:\n\n```\ntransposed_suffixes = (\n    \".attn.c_attn.weight\", \".attn.c_proj.weight\",\n    \".mlp.c_fc.weight\", \".mlp.c_proj.weight\",\n)\n...\ntensor = source[name].t() if name.endswith(transposed_suffixes) else source[name]\ndestination.copy_(tensor)\n```\n\nThe loader validates every key and every shape before copying anything, so a late mismatch cannot leave a half-loaded model behind.\n\n**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.\n\nThat 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.\n\nThe 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.\n\n| Stage (cumulative) | Median ms / update | Tokens/s | vs previous | \n|---|---|---|---|\n| baseline, FP32, eager attention | 53.750 | 4,762.8 | 1.000× | \n| + TF32 matmul | 53.043 | 4,826.3 | 1.013× | \n| + BF16 autocast | 59.097 | 4,331.9 | 0.898× | \n| + `torch.compile` | 36.790 | 6,958.4 | 1.606× | \n| + SDPA, flash kernel only | 36.171 | 7,077.4 | 1.017× | \n| + vocabulary padded to 50,304 | 36.227 | 7,066.6 | 0.998× | \n\nThe 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).\n\nWhat I took from it:\n\n`torch.compile` stage was the largest single step:`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.\nGradient 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.\n\nWeek 12 is a separate model. It starts from random weights, not from OpenAI's.\n\n`sample-10BT`, pinned to a fixed dataset revision, so the run can be traced back to exact documents.`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.\nB = 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.\n\nThe run made 19,586 updates and processed 80,224,256 tokens in 60.20 minutes. Validation NLL went from 11.013 to 4.984965.\n\nHellaSwag 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:\n\n`Rowan/hellaswag` from the Hugging Face Hub, pinned to a revision.\n\n```\nlosses = F.cross_entropy(\n    logits[..., :50257].float().reshape(-1, min(50257, logits.shape[-1])),\n    targets.reshape(-1), reduction=\"none\").reshape_as(targets)\ntotals = (losses * mask).sum(-1)   # mask: ending positions only\nmeans = totals / mask.sum(-1)      # acc_norm uses the mean\n```\n\nOn 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.\n\n**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.\n\nThe 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.\n\n**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.\n\n**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.\n\n**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.\n\n**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.\n\nTwo 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.\n\n| Evaluation | L4 checkpoint | G4 continuation | OpenAI GPT-2 | \n|---|---|---|---|\n| FineWeb validation NLL (fixed 32,768 targets) | 4.984965 | 3.665616 | not measured | \n| HellaSwag, indices 0–999 | 27.6% | 32.3% | 33.6% | \n| HellaSwag, indices 1,000–1,999 | not measured | 30.5% | 33.7% | \n\nIndices 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%.\n\nBoth models answer the same questions, so I compare them pairwise instead of treating the two accuracies as independent:\n\n| Cohort | Only mine correct | Only GPT-2 correct | Paired bootstrap 95% CI (mine − GPT-2) | Exact McNemar p | \n|---|---|---|---|---|\n| 0–999 | 88 | 101 | [−4.00, +1.40] points | 0.383 | \n| 1,000–1,999 | 58 | 90 | [−5.60, −0.80] points | 0.0106 | \n\nThe 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.\n\nSame prompt, seed 42, temperature 0.8, top-k 50, at most 48 new tokens. At the start of G4:\n\nThe 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,\" ...\n\nAt the end of G4:\n\nThe 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. ...\n\nThe 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.\n\nThe evidence check runs without a GPU, a checkpoint or a dataset download:\n\n```\ngit clone https://github.com/muend/neuron-to-gpt\ncd neuron-to-gpt\npython experiments/g4/analyze_results.py --check\n```\n\nThe 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.\n\nIf you spot a flaw in the evaluation setup, I would like to hear about it in the comments.", "url": "https://wpnews.pro/news/building-gpt-2-124m-in-pytorch-weight-parity-a-speed-ladder-and-about-150-gpu-of", "canonical_source": "https://dev.to/muend/building-gpt-2-124m-in-pytorch-weight-parity-a-speed-ladder-and-about-150-gpu-minutes-of-my-own-18dn", "published_at": "2026-11-26 17:39:30+00:00", "updated_at": "2026-11-26 17:47:23.531187+00:00", "lang": "en", "topics": ["artificial-intelligence", "machine-learning", "large-language-models", "ai-research", "ai-tools"], "entities": ["OpenAI", "GPT-2", "PyTorch", "Hugging Face", "Andrej Karpathy", "NVIDIA L4", "A100", "HellaSwag"], "also_reported_by": [], "takeaway": "A full-logit parity test with rtol=atol=1e-4 across English, Turkish and emoji prompts caught the silent 768x768 attention c_proj transpose bug that a shape check alone would miss, with max logit differences of 5.3e-05 to 8.4e-05 on an A100.", "recommendation": {"advice": "Compare full logits against reference weights at rtol=atol=1e-4 on multilingual and emoji prompts, and validate every key and shape before copying, since square projections load silently when untransposed.", "playbook": "evals-testing", "playbook_url": "https://wpnews.pro/playbooks/evals-testing"}, "alternates": {"html": "https://wpnews.pro/news/building-gpt-2-124m-in-pytorch-weight-parity-a-speed-ladder-and-about-150-gpu-of", "markdown": "https://wpnews.pro/news/building-gpt-2-124m-in-pytorch-weight-parity-a-speed-ladder-and-about-150-gpu-of.md", "text": "https://wpnews.pro/news/building-gpt-2-124m-in-pytorch-weight-parity-a-speed-ladder-and-about-150-gpu-of.txt", "jsonld": "https://wpnews.pro/news/building-gpt-2-124m-in-pytorch-weight-parity-a-speed-ladder-and-about-150-gpu-of.jsonld"}}