Let's reproduce GPT-2 (124M)
Overview
Andrej Karpathy builds a GPT-2 124M language model in PyTorch, first matching OpenAI’s released checkpoint and then training new weights from scratch. He develops the model and data pipeline, accelerates training with BF16, torch.compile, FlashAttention, fused AdamW, and eight-GPU DistributedDataParallel, then trains on FineWeb-Edu and evaluates against GPT-2 using validation loss and HellaSwag.
Key takeaways
- A GPT-2 124M replica can be trained from scratch with 12 layers, 768 channels, and a 50,257-token vocabulary, then evaluated against OpenAI’s released checkpoint.
- Performance improvements come from multiple layers of optimization: BF16 reduces activation traffic, `torch.compile` fuses operations, FlashAttention avoids materializing the attention matrix, and fused AdamW reduces update overhead.
- Gradient accumulation matches a large batch only when each microbatch’s mean loss is divided by the number of accumulation steps before backpropagation.
- DistributedDataParallel scales training by giving each GPU distinct data and averaging gradients, while synchronization can be skipped on intermediate accumulation steps.
- On FineWeb-Edu, one epoch over a 10-billion-token sample surpasses GPT-2 124M’s roughly 29.5 percent HellaSwag score, but benchmark overlap and dataset differences limit the strength of that comparison.
- Sequentially replaying the same document order can create periodic training-loss patterns; shuffling documents and shards between epochs is an important data-loader improvement.
Chapters
- The target is the smallest GPT-2 model, with 124 million parameters, 12 Transformer layers, and 768 channels.
- OpenAI’s GPT-2 model series ranges from 124M to roughly 1.558B parameters, illustrating how model scale affects downstream performance.
- Karpathy sets the goal of matching or beating the released GPT-2 checkpoint by training from random initialization.
- OpenAI’s original GPT-2 implementation uses TensorFlow; Karpathy uses Hugging Face Transformers to access a PyTorch-compatible model and weights.
- The Hugging Face model named `gpt2` is the 124M checkpoint; `gpt2-xl` refers to the much larger model.
- Extracting the state dictionary exposes parameter names and tensor shapes for the model.
- GPT-2 removes the Transformer encoder and encoder-decoder cross-attention, leaving a decoder-only architecture.
- GPT-2 moves layer normalization before attention and the MLP, and adds a final layer normalization before the language-model head.
- Karpathy uses the Hugging Face parameter naming scheme as a blueprint for a compact implementation that can load the released weights.
- Each block applies layer normalization before self-attention and before the feed-forward network.
- Residual connections preserve a direct pathway for activations and gradients through the network.
- Attention combines information across sequence positions, while the MLP transforms each token position independently.
- The MLP uses two linear projections with GPT-2’s approximate GELU, written as `gelu(..., approximate="tanh")` in PyTorch.
- A single combined query-key-value projection handles attention inputs, then tensor reshaping separates the heads.
- Causal masking prevents tokens from attending to future positions; the attended values are combined across heads.
- Karpathy copies matching state-dictionary tensors into the hand-built GPT-2 module.
- Attention-mask buffers are skipped because they are not learned parameters.
- Some weights need transposition to match PyTorch’s linear-layer layout; successful loading verifies the architecture and naming.
- The model accepts token indices shaped `(B, T)`, where `B` is batch size and `T` is sequence length.
- Token embeddings and learned positional embeddings are added before passing through the Transformer blocks.
- The language-model head returns logits shaped `(B, T, 50257)`, predicting the next token at every position.
- Karpathy recreates the Hugging Face sampling example using the GPT-2 tokenizer from OpenAI’s `tiktoken` library.
- The prefix “Hello, I’m a language model” is encoded as token IDs, repeated across five batch rows.
- The input tensor is moved to the same device as the model before generation.
- Each generation step takes the last-position logits, applies softmax, and samples a new token.
- Top-k sampling with `k=50` discards lower-probability tokens before renormalizing, keeping generations near likely continuations.
- Generated token IDs are appended to the context and decoded with `tiktoken`; Hugging Face’s pipeline differs in some sampling details.
- A model created with the default GPT-2 configuration uses random PyTorch initializers and initially generates nonsensical text.
- Karpathy selects CUDA when available, Apple Silicon’s MPS backend otherwise, and CPU as a fallback.
- Creating position indices on the input tensor’s device prevents CPU/GPU tensor mismatches.
- The roughly one-million-character Tiny Shakespeare text file is used as a small debugging dataset.
- GPT-2 tokenization compresses the text to roughly one token per three characters.
- The first training task is to convert the token stream into batches of independent sequences.
- A flat token sequence can be reshaped into a `(B, T)` batch using `view`.
- The target batch is the input sequence shifted by one token, so each position learns to predict its successor.
- Fetching `B*T + 1` tokens provides the final target needed for the last input position.
- The model’s `(B, T, vocab_size)` logits are flattened to `(B*T, vocab_size)` for PyTorch cross-entropy.
- The target IDs are flattened to `(B*T,)`, with each label identifying the next token.
- A random model’s expected loss is near `-log(1/50257)`, approximately 10.82, providing an initialization sanity check.
- The debugging loop uses AdamW with a learning rate of `3e-4`.
- Gradients must be cleared before each backward pass because PyTorch accumulates them by default.
- Driving loss down on a fixed small batch confirms that the model can memorize examples and that the optimization path works.
- The data loader tokenizes the full text once and advances through it in chunks of `B*T` tokens.
- Each chunk includes one extra token for the shifted target, then returns aligned `X` and `Y` tensors.
- The first run processes only 50 batches from a dataset containing about 338,000 tokens.
- GPT-2 shares one weight matrix between the token embedding table and the final language-model projection.
- The tied matrix has shape `50257 × 768`, sharing roughly 40 million parameters.
- Weight tying applies the same learned token relationships at input and output and reduces the number of distinct parameters.
- OpenAI’s released GPT-2 code initializes linear and embedding weights with a normal distribution around standard deviation `0.02`.
- Linear biases are initialized to zero, while layer-normalization scale and offset remain at one and zero.
- The implementation applies custom initialization across the model’s submodules to reproduce these settings.
- GPT-2’s initialization scales residual-branch weights by the inverse square root of the number of residual layers.
- Each Transformer block contributes two residual branches, one for attention and one for the MLP.
- This scaling helps control activation growth as contributions accumulate through the residual stream.
- Karpathy’s machine has eight NVIDIA A100 SXM GPUs with 80 GB of memory each.
- Standard FP32 matrix multiplication is limited to about 19.5 TFLOPs per A100, compared with much higher low-precision tensor-core throughput.
- Training performance depends on both arithmetic throughput and the time required to move activations and weights through memory.
- On supported NVIDIA GPUs, PyTorch can use TF32 matrix multiplications by setting `torch.set_float32_matmul_precision("high")`.
- TF32 truncates input mantissa precision internally while retaining FP32 accumulation and output.
- The measured training throughput improves by roughly three times, below the theoretical eightfold arithmetic gain because memory traffic remains a bottleneck.
- Karpathy uses `torch.autocast` with `dtype=torch.bfloat16` around the model forward pass and loss calculation.
- BF16 retains FP32’s exponent range but has fewer mantissa bits, usually avoiding the gradient-scaling requirement of FP16.
- Model parameters remain FP32 while selected activations and matrix operations use BF16.
- `torch.compile(model)` reduces Python overhead and can combine operations into more efficient GPU kernels.
- On the measured run, compilation reduces iteration time from about 300 ms to 129 ms, roughly a 2.3× improvement.
- Kernel fusion avoids repeatedly writing intermediate results to GPU memory between simple operations.
- A GPU has high-bandwidth memory outside the compute chip and smaller, faster on-chip storage such as L2, L1, and registers.
- Repeated reads and writes to HBM can dominate runtime even when tensor cores execute matrix multiplications quickly.
- Fusing operations lets data remain on-chip longer, reducing expensive memory round trips.
- FlashAttention replaces the usual sequence of attention operations with a fused, memory-aware algorithm.
- Its online softmax method avoids materializing the full sequence-by-sequence attention matrix in HBM.
- Calling PyTorch’s scaled dot-product attention enables the optimized path and reduces iteration time from about 130 ms to roughly 96 ms.
- The tokenizer vocabulary size, 50,257, is awkward for kernels that operate on power-of-two-aligned tiles.
- Padding the model’s output dimension to 50,304 improves the measured iteration time by about four percent on the PyTorch nightly version used.
- The extra output classes are never tokenizer inputs and are learned as effectively unused predictions.
- The GPT-2 paper provides limited training details, so Karpathy supplements it with the more specific GPT-3 paper.
- The models share a closely related architecture, although GPT-3 uses a 2,048-token context and much larger training runs.
- GPT-3’s 12-layer, 768-channel configuration provides a useful reference for the GPT-2 124M learning rate and batch size.
- The optimizer uses Adam settings with beta values `0.9` and `0.95`, and epsilon `1e-8`.
- Global gradient norm clipping limits the combined gradient magnitude to `1.0` after backpropagation.
- Logging the unclipped norm helps reveal early training spikes or later optimization instability.
- The schedule linearly warms up to a peak learning rate, then cosine-decays toward ten percent of that peak.
- The GPT-3 reference describes warmup over 375 million tokens and decay over a longer token horizon.
- Karpathy implements the scheduler directly so its step-by-step behavior is explicit and easy to inspect.
- The optimizer applies weight decay of `0.1` to matrix weights and embeddings, but not to biases or one-dimensional layer-normalization parameters.
- PyTorch parameter groups allow decayed and non-decayed tensors to use different settings.
- When available, fused AdamW updates many parameters with fewer kernel launches and modestly reduces iteration time.
- The GPT-3 reference batch is about `2^19`, or 524,288 tokens per optimizer step.
- A microbatch of 16 sequences at 1,024 tokens processes 16,384 tokens per forward-backward pass.
- Accumulating gradients over 32 microsteps simulates the target batch size without requiring it to fit in GPU memory.
- PyTorch cross-entropy averages over batch tokens, while repeated backward passes add gradients together.
- Dividing each microbatch loss by the number of accumulation steps makes the accumulated gradient match a single large batch.
- A small regression example demonstrates that omitting this division produces gradients four times too large for four microbatches.
- `torchrun --standalone --nproc_per_node=8` launches one training process for each of the eight GPUs.
- Each process uses its rank and local rank to select its GPU and identify its share of the work.
- The rank-zero master process handles shared logging and checkpointing to avoid duplicated output.
- The data loader receives each process’s rank and world size so separate GPUs consume different token ranges.
- Each rank advances through the stream by the total number of tokens processed across all ranks.
- The simple sequential loader is adequate for the initial distributed test but later needs better document shuffling.
- DistributedDataParallel averages gradients across GPUs during backpropagation, keeping model updates synchronized.
- During gradient accumulation, Karpathy suppresses synchronization on intermediate microsteps and synchronizes on the final one.
- Loss statistics are reduced across ranks before the master process logs them; eight GPUs reach roughly 1.5 million tokens per second.
- GPT-2 trained on WebText, a dataset built from outbound Reddit links with at least three karma; the original dataset was not released.
- GPT-3’s mixture included sources such as Common Crawl, WebText, books, and Wikipedia.
- Common Crawl requires filtering because raw crawls contain substantial spam, duplicated text, and low-quality material.
- Karpathy selects Hugging Face’s FineWeb-Edu, an educational subset of filtered web text.
- The full dataset is much larger, but the experiment uses a 10-billion-token sample.
- FineWeb-Edu’s filtering uses language-model-based judgments to select educational content.
- Each document begins with GPT-2’s end-of-text token, ID `50256`, followed by its encoded content.
- Tokens are stored as NumPy `uint16` arrays, which can represent every GPT-2 token ID while reducing storage needs.
- The preprocessing script writes shards of 100 million tokens, including a separate validation shard.
- A 10-billion-token run with 524,288 tokens per optimizer step requires about 19,073 steps.
- Warmup over 375 million tokens corresponds to approximately 715 steps at that batch size.
- The data loader is extended to move through training and validation shards.
- Karpathy increases the per-GPU microbatch to 64 sequences at 1,024 tokens, eliminating gradient accumulation on the eight-GPU machine.
- The run processes about 1.5 million tokens per second and is projected to take roughly 1.7 hours.
- The learning rate warms toward the GPT-3-derived peak of `6e-4`.
- The training loop periodically evaluates a separate validation shard without gradients.
- Karpathy samples text from the model every 100 steps and logs training and validation losses.
- A dedicated PyTorch random-number generator keeps sampling randomness separate from the training RNG state.
- HellaSwag presents a context and four possible continuations, one of which best fits everyday physical and social knowledge.
- Its adversarially generated distractors made the benchmark challenging for language models when it appeared in 2019.
- The benchmark later became much easier for modern models, but its gradual accuracy gains provide a useful early training signal.
- The evaluation scores each continuation as a token sequence rather than asking the small model to output a multiple-choice label.
- Variable-length options are padded and masked so only continuation tokens contribute to their average loss.
- The option with the lowest average token loss is selected; released GPT-2 124M scores about 29.5 percent, above the 25 percent chance baseline.
- HellaSwag examples are divided across DDP ranks, then counts are summed to produce a combined accuracy.
- The training script periodically evaluates validation loss, HellaSwag accuracy, and generated samples.
- Karpathy temporarily disables `torch.compile` because it causes errors in the sampling and evaluation code.
- At roughly 10,000 steps, generations are less random and increasingly refer to being a language model.
- The text is still repetitive and imperfect, reflecting a model partway through its training run.
- The training log captures the changing loss and benchmark results for later visualization.
- One pass over the 10-billion-token FineWeb-Edu sample surpasses the released GPT-2 124M checkpoint on HellaSwag.
- Karpathy notes that the benchmark and training-data distributions may overlap, so the result is not a definitive generalization comparison.
- The newer educational data may also be higher quality per token than GPT-2’s original WebText.
- Extending the run to four epochs trains on roughly 40 billion tokens overnight.
- HellaSwag accuracy reaches about 33.24 percent, approaching the GPT-3 124M reference discussed in the comparison.
- Generated samples become more coherent, though the data-ordering issues remain.
- The sequential loader repeats documents in the same order each epoch, which can create periodic loss patterns and unwanted document adjacency.
- Shuffling document order and shards at epoch boundaries would improve the data stream.
- Karpathy notes that higher learning rates may train faster and adds model checkpoints; resuming exactly also requires optimizer state and RNG state.
- The trained GPT-2 is a pretrained next-token model, not a chat assistant; supervised fine-tuning would require conversational data and continued training.
- Karpathy compares nanoGPT-style PyTorch training with `llm.c`, a direct CUDA implementation of GPT-2/GPT-3 training.
- Both implementations produce matching losses and gradient norms in the comparison, while `llm.c` runs faster on the tested setup.
- The project builds GPT-2 124M from scratch and reaches or exceeds the released checkpoint on selected measures after a short training run.
- Remaining issues include FineWeb-Edu ordering, data-loader shuffling, and `torch.compile` failures during evaluation and generation.
- Karpathy points to the build-nanoGPT commit history, nanoGPT, `llm.c`, and the Zero to Hero community for further exploration.
Transcript excerpt
0:00 hi everyone so today we are going to be continuing our Zero to Hero series and in particular today we are going to reproduce the gpt2 model the 124 million version of it so when openi released gpt2 this was 2019 and they released it with this blog post on top of that they released this paper and on top of that they released this code on GitHub so open a/ gpt2 now when we talk about reproducing gpt2 we have to be careful because in particular in this video we're going to be reproducing the 124 million parameter model so the thing to realize is that there's always a miniseries when these are releases are made so there are the gpt2 miniseries made up of models at different sizes and usually the biggest model is called the
0:46 gpt2 but basically the reason we do that is because you can put the model sizes on the x-axis of plots like this and on the Y AIS you put a lot of uh Downstream metrics that you're interested in like translation summarization question answering and so on and you can chart out these scaling laws so basically as the model size increases you're getting better and better at Downstream metrics and so in particular for gpt2 if we scroll down in paper there are four models in the gpt2 miniseries starting at 124 million all the way up to 1558 million now the reason my numbers the way I say them disagree with this table is that this table is wrong if you actually go to the uh gpt2 uh GitHub repo they sort of say that um there was an error in how they added up
1:33 the parameters but basically this is the 124 million parameter model Etc so the
This is the start of the transcript. Save this video free for the whole transcript, searchable and time-coded.
Related notes
Summary, takeaways, and chapters were generated by AI from the video's transcript and may contain errors. The video belongs to its creator, Andrej Karpathy.