GPT-2 in PyTorch nachgebaut: Gewichtspaeritaet, Tempo-Bestenliste und rund 150 GPU-Minuten Training
Ein Entwickler hat GPT-2 (124M) in PyTorch implementiert und dabei drei Ebenen der Reproduktion erreicht: identische Funktion mit OpenAI-Gewichten, ein schneller Trainings-Loop und ein Training von zufaelligen Gewichten aus, das tatsaechlich etwas lernt.

„Ich habe GPT-2 implementiert" kann drei sehr verschiedene Dinge bedeuten. Man kann OpenAIs Gewichte in den eigenen Code laden und zeigen, dass er dieselbe Funktion berechnet. Man kann den Training-Loop schnell machen. Oder man kann von zufälligen Gewichten ausgehen und ein Modell trainieren, das tatsächlich etwas lernt. Alle drei Dinge sind in meinem Repository neuron-to-gpt geschehen, meinen wöchentlichen Einreichungen für ein zwölfwöchiges KI-Programm, das von einem einzelnen Neuron bis zu GPT-2 führte. Die Zahlen auseinanderzuhalten erwies sich als schwieriger als sie zu erzeugen.
Die GPT-2-Wochen folgen dem Aufbau von Andrej Karpathys Vorlesung „Let's reproduce GPT-2 (124M)", daher wird das Modell selbst vertraut aussehen. Dieser Beitrag handelt davon, was ich darum herum ergänzt habe: einen Paritätstest über die vollständigen Logits auf englischen, türkischen und Emoji-Prompts, der den Gewichtsimport absichert; eine Stufenleiter zur Geschwindigkeit, bei der jede Stufe einzeln gemessen wird und die Flash-Stufe nicht lautlos zurückfallen kann; einen fortsetzbaren Trainingslauf, dessen Unterbrechung im Protokoll festgehalten ist; und einen gepaarten Vergleich gegen GPT-2 auf einer zurückgehaltenen HellaSwag-Kohorte.
Standard-GPT-2 small: 12 Blöcke, 12 Heads, Breite 768, 1.024 Positionen, Pre-LayerNorm, tanh-näherungsweise GELU, gelernte absolute Positionen und eine fusionierte Q/K/V-Projektion. Das Token-Embedding und die Ausgabeschicht teilen sich eine Matrix (Weight Tying), was 50.257 × 768 = 38.597.376 Parameter spart: Das Modell mit geteilten Gewichten hat 124.439.808 eindeutige Parameter, das ohne geteilte Gewichte hätte 163.037.184.
Die Initialisierung folgt GPT-2: Standardabweichung 0,02 für Gewichtsmatrizen und 0,02/√(2L) für die beiden Restausgabeprojektionen in jedem Block. Jeder Block fügt zwei Beiträge zum Residual-Stream hinzu, weshalb die Varianz des Streams ohne die kleinere Skalierung mit der Tiefe wachsen würde.
Um die Implementierung zu prüfen, importiere ich die veröffentlichten OpenAI-Gewichte (die Hugging-Face-Kopie, auf eine feste Revision fixiert) in meine eigenen Module und vergleiche die Ausgaben.
Die Falle steckt im Import. Hugging Faces GPT-2 verwendet eine historische Conv1D-Schicht, die Gewichte als (Eingabe, Ausgabe) speichert. nn.Linear erwartet (Ausgabe, Eingabe). Vier Gewichtsmatrizen pro Block müssen also transponiert werden. Bei dreien von ihnen schlägt eine vergessene Transposition laut mit einem Shape-Fehler fehl. Die Aufmerksamkeitsausgabeprojektion ist 768 × 768, sodass eine fehlende Transposition dort ohne Beschwerden geladen wird und stillschweigend eine andere Funktion berechnet.
Aus 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 ) Vollbildmodus öffnen Vollbildmodus schließen Der Loader validiert jeden Schlüssel und jede Form, bevor irgendetwas kopiert wird, sodass ein spät auftretender Mismatch kein halb geladenes Modell hinterlassen kann.
Der Paritätscheck vergleicht vollständige Logits, keine Stichprobe. Beide Modelle erhalten dieselbe Eingabe in FP32, mit Eager-Attention, ausgeschaltetem TF32 und ausgeschaltetem Dropout, und jedes Logit muss innerhalb von rtol = atol = 1e-4 übereinstimmen. Ich habe bewusst drei Prompts verwendet: einen englischen Satz, einen türkischen und einen gemischten String mit einem Emoji, damit auch Multi-Byte-BPE-Pfade durchlaufen werden. Auf einer A100 lag die größte absolute Differenz pro Prompt zwischen 5,3e-05 und 8,4e-05, und alle drei bestanden; dieselbe Prüfung bestand auch auf einer T4.
Das beweist, dass mein Code mit denselben Gewichten dieselbe Funktion wie die Referenz berechnet. Es sagt nichts darüber aus, ob mein Code lernen kann. Dafür hat Woche 10 eine bewusst eng gefasste Diagnose: 300 Updates auf einem festen Batch (4 × 32 Tokens) von zufälligen Gewichten aus. Der Loss sank von 11,056 auf etwa 0,0001, und die Token-Genauigkeit erreichte 100 %. Das ist Auswendiglernen eines einzelnen Batches. Es zeigt, dass Gradienten fließen und der Optimizer Schritt für Schritt arbeitet; es ist kein Beleg für Generalisierung, und ich berichte es nie als solchen.
Die Frage in Woche 11 war einfach: Welche der üblichen Beschleunigungen hilft auf der GPU, die ich habe? Statt alles auf einmal zu aktivieren, wird jede Stufe zusätzlich zur vorherigen hinzugefügt und separat gemessen.
Die Bedingungen sind so wichtig wie die Zahlen: B = 2, T = 128, 5 Warmup-Updates, 20 gemessene Updates pro Stufe, ein Durchlauf, auf einer NVIDIA L4. Jedes gemessene Update umfasst Datentransfer, Forward, Backward, Unscale/Clip und den AdamW-Schritt, mit einer CUDA-Synchronisation pro Schritt. Kompilierzeit und Warmup sind ausgenommen (Kompilierung plus Warmup dauerte für diese Stufe etwa 42 Sekunden).
Auch die Gradientenakkumulation erhält eine Korrektheitsregel: K Micro-Batches mit jeweils gleichen Tokenzahlen tragen je loss / K bei, sodass der aufsummierte Gradient dem Gradienten des mittleren Losses über den kombinierten Batch entspricht. Clipping und der AdamW-Schritt erfolgen einmal pro Update, nach dem Unscaling.
Woche 12 ist ein eigenes Modell. Es startet von zufälligen Gewichten, nicht von denen OpenAIs.
B = 4, T = 256, Akkumulation 4 (4.096 Tokens pro Update), BF16, SDPA, torch.compile, ein Warmup von 100 Updates und ein Budget von 60 Minuten Echtzeit. Der Checkpoint ( last.pt ) speichert nicht nur Gewichte, sondern auch den AdamW- und Scaler-Zustand, die Position des Data Loaders und den RNG-Zustand, sodass ein Colab-Disconnect nicht stillschweigend den Datenstrom oder den Zeitplan neu startet.
Der Lauf absolvierte 19.586 Updates und verarbeitete 80.224.256 Tokens in 60,20 Minuten. Die Validierungs-NLL sank von 11,013 auf 4,984965.
HellaSwag liefert einen Kontext und vier Endungen; das Modell wählt die Endung, die es für am wahrscheinlichsten hält. Kleine Protokollentscheidungen verschieben den Wert um ganze Punkte, deshalb habe ich alle fixiert:
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: nur Endungspositionen means = totals / mask. sum ( - 1 ) # acc_norm nutzt den Mittelwert Vollbildmodus öffnen Vollbildmodus schließen Auf den ersten 1.000 Validierungsbeispielen erreichte mein 60-Minuten-Modell 27,6 % (Zufallsniveau ist 25 %). OpenAI GPT-2 erzielte unter identischem Protokoll 33,6 %. Achtzig Millionen Tokens sind ein kleines Experiment, keine Reproduktion eines Pretrainings; eine Lücke ist zu erwarten, auch wenn dieser Lauf deren Ursachen nicht isoliert.
Eine Anmerkung zu den absoluten Zahlen. Karpathys build-nanogpt-Skript meldet mit derselben acc_norm im Completion-Stil 29,55 % für GPT-2 124M auf allen 10.042 Validierungsbeispielen. Meine 1.000-Beispiel-Slices ergeben für GPT-2 33,6 % und 33,7 %, und das Wilson-Intervall für 33,6 % (etwa 30,7 % bis 36,6 %) erreicht 29,55 % nicht. Die ersten 2.000 Beispiele des fixierten Rowan/hellaswag-Splits sind also leichter als die Gesamtmenge, oder etwas in der Datenquelle unterscheidet sich; ich habe die vollständige Menge nicht durchlaufen, um das herauszufinden. Die Werte in diesem Beitrag sind daher untereinander vergleichbar, unter einem Protokoll und auf denselben Indizes, nicht aber mit veröffentlichten Werten über die volle Menge.
Das letzte Experiment nimmt exakt diesen L4-Checkpoint, prüft seinen Hash und setzt das Training auf einer NVIDIA RTX PRO 6000 Blackwell GPU für 90 Minuten fort. Es wird nicht von OpenAI-Gewichten gestartet.
Einstellungen: B = 8, T = 1.024, Akkumulation 4 (32.768 Tokens pro Update), BF16, SDPA, torch.compile und fused AdamW mit β = (0,9, 0,95), ε = 1e-8, Weight Decay 0,1 auf Matrizen und Gradient Clipping bei 1,0. Die Lernrate wärmt über 30 erfolgreiche Updates auf und folgt dann einer Cosinus-Hüllkurve, an die Echtzeit gekoppelt ist, von 3e-4 hinab bis 3e-5, sodass der Zeitplan endet, wenn das Budget endet, unabhängig vom Durchsatz.
Frische Daten, geprüft gegen den alten Lauf. Ein neuer Trainingspool von 200 Mio. Tokens wurde aus derselben fixierten FineWeb-Edu-Revision gezogen. Jedes Dokument, dessen SHA-256 exakt mit einem Dokument im früheren L4-Trainings- oder Validierungsset übereinstimmt, wurde entfernt. Der 131.072-Token-Validierungsshard wurde bytegenau übernommen, sodass die L4- und G4-Validierungszahlen dieselben 32.768 Targets messen.
Die Fortsetzungs-Buchführung ist Teil des Ergebnisses. Die erste Sitzung war gegen eine Uhren-Frist geplant. Sie wurde nach 3.989 committeten Updates unterbrochen und vom verifizierten Checkpoint fortgesetzt; beim Fortsetzen wurde die fristbasierte Begrenzung entfernt und das Gesamtbudget über beide Sitzungen auf 90 Minuten gesetzt (die Pause zwischen den Sitzungen zählt nicht). Die 3.989 Updates blieben erhalten, und 16.384 Tokens aus einem unvollständigen Micro-Batch wurden erneut gelesen. Quellversion, alte und neue Budgeteinstellungen und der Checkpoint-Hash sind alle unter resumes in training.json dokumentiert. Eine Loss-Kurve ohne ihre Fortsetzungsgeschichte ist schwer zu vertrauen.
Ergebnis: 38.061 Updates, 1.247.182.848 verarbeitete Tokens, 90,01 Minuten, etwa 230.933 Tokens/s über die Echtzeit. Die Validierungs-NLL fiel von 4,984965 auf 3,665616.
Zwei Einschränkungen begleiten diese Zahlen. Verarbeitete Tokens sind keine einzigartigen Daten: Der 200-Mio.-Token-Pool wurde etwa 6,24-mal gesehen. Und der Durchsatz ist kein kontrollierter Vergleich mit dem L4-Lauf, da Kontextlänge, Batch, Daten und Hardware alle geändert wurden.
Die Indizes 0 bis 999 wurden bereits in Woche 12 verwendet, zeigen dort also nur Kontinuität: dieselben Beispiele gingen von 27,6 % auf 32,3 %. Die Indizes 1.000 bis 1.999 waren im Voraus als Hauptvergleich reserviert, und der Checkpoint wurde nach Validierungs-Loss ausgewählt, nie nach HellaSwag. Auf dieser zurückgehaltenen Kohorte erreicht mein Modell 30,5 % und GPT-2 33,7 %.
Beide Modelle beantworten dieselben Fragen, daher vergleiche ich sie paarweise, statt die beiden Genauigkeiten als unabhängig zu behandeln:
Das Bootstrap-Verfahren verwendet 20.000 Resamples mit dem Seed 20261108 und geht von unabhängigen Beispielen aus, weshalb es lediglich ein grobes Unsicherheitsmaß darstellt. Plain gelesen: Bei der ersten Kohorte können die Daten die beiden Modelle nicht unterscheiden, bei der Held-out-Kohorte liegt GPT-2 vorn. Es gibt keinen Equivalenz-Befund, und nichts hier sagt etwas über Chat, Code oder reasoning aus.
Gleicher Prompt, Seed 42, Temperatur 0.8, top-k 50, höchstens 48 neue Token. Zu Beginn von 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,"...
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....
Die Sätze sind besser geformt, aber das Modell wiederholt sich weiterhin und verliert einige Zeilen später den Faden. Ein einzelnes Sample ist eine Illustration, keine Auswertung.
Der Evidence-Check läuft ohne GPU, Checkpoint oder Dataset-Download:
git clone https://github.com/muend/neuron-to-gpt cd neuron-to-gpt python experiments/g4/analyze_results.py --check Enter fullscreen mode Exit fullscreen mode Der Check rechnet die Datei-Hashes, die Token- und Update-Buchhaltung sowie die korrekten Zählungen anhand der gespeicherten NLL-Scores pro Beispiel neu; das Modell wird dabei nicht erneut ausgeführt. Der G4-Bericht samt seiner Evaluationsdateien pro Beispiel liegt in experiments/g4/results/nvidia_rtx_pro6000/, die Speed-Ladder in week11/results/nvidia_l4/ und der Paritätsbericht in week10/results/. Das README zu Woche 12 listet das HellaSwag-Skript von build-nanogpt als Referenz-Evaluationsprotokoll auf.
Wenn Sie einen Fehler im Evaluationssetup entdecken, würde ich das gerne in den Kommentaren erfahren.
Automatisch übersetzt. Das Original auf Englisch ist unten aufklappbar.
Original (Englisch) anzeigen
"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.
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.
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 ) Enter fullscreen mode Exit fullscreen mode 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.
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.
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).
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 is a separate model. It starts from random weights, not from OpenAI's.
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 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:
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 Enter fullscreen mode Exit fullscreen mode 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.
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.
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:
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.
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,"...
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.
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 Enter fullscreen mode Exit fullscreen mode 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.