Let's reproduce GPT-2 (124M)

Andrej Karpathy

Karpathy rebuilds GPT-2 (124M) from scratch, 11x faster, and matches OpenAI on HellaSwag

In a four-hour build, Andrej Karpathy writes GPT-2 in PyTorch, cuts step time from 1,000 ms to 90 ms, and trains it on 8 GPUs. A run on 10 billion FineWeb-Edu tokens passes OpenAI's checkpoint on HellaSwag.

In a nearly four-hour session published on June 9, 2024, Andrej Karpathy reproduces the 124 million parameter GPT-2 model that OpenAI released in 2019. He writes the network, speeds up training roughly elevenfold, follows the GPT-3 paper's hyperparameters, and trains on eight A100 GPUs. A run of about 10 billion tokens beats OpenAI's checkpoint on HellaSwag, a sentence-completion benchmark, and a longer overnight run comes close to the GPT-3 124M result.

Building the GPT-2 network and loading OpenAI's weights

He starts by loading OpenAI's weights through Hugging Face, because the original code is in TensorFlow, and samples text to confirm the target works. He then writes his own model in under 100 lines, matching Hugging Face's naming so the weights drop in. GPT-2 is a decoder-only Transformer with layer norms moved before attention and the MLP, plus one extra at the end. He uses the approximate GELU activation because GPT-2 did.

Two details get attention. The token embedding and the final output layer share one weight matrix, which saves about 40 million parameters, roughly 30 percent of the model. Initialisation follows OpenAI's code: standard deviation 0.02, with residual-path weights scaled by one over the square root of the number of residual layers, to stop activations growing with depth.

Code editor showing a GPT class with a ModuleDict holding token and position embeddings, a list of blocks and an output head.
The GPT-2 skeleton is laid out as an nn.Module whose names mirror the Hugging Face weights.

Making training fast: TF32, bfloat16, torch.compile and Flash Attention

The baseline on an A100 is about 1,000 ms per step in float32. Each change then cuts it:

  • TF32: about 333 ms. Matrix multiplies run at reduced internal precision, but the code is otherwise unchanged. The speedup is well short of the promised 8x because training is limited by memory traffic.
  • bfloat16 autocast: about 300 ms. It keeps float32's number range, so no gradient scaler is needed.
  • torch.compile: about 130 ms. It removes Python overhead and fuses operations, so data makes fewer round trips to GPU memory.
  • Flash Attention: about 96 ms. It does more arithmetic but never writes the full attention matrix to memory.
  • Vocabulary 50257 to 50304: about 93 ms. Padding to a number with many factors of two helps GPU kernels, so extra work runs faster.

A fused AdamW optimizer takes it to 90 ms.

Diagram of a CPU, RAM, and a GPU with high bandwidth memory, used to explain memory round trips.
Explaining how torch.compile fuses operations to avoid repeated trips between GPU memory and the chip.

GPT-3 hyperparameters, gradient accumulation and multi-GPU training

Because GPT-3 is described in more detail, he borrows its settings: AdamW betas of 0.9 and 0.95, gradient norm clipping at 1.0, weight decay of 0.1 on matrices and embeddings only, and a cosine learning rate schedule with warmup. He skips the batch size ramp to keep the arithmetic simple.

To reach the paper's batch of about half a million tokens (2 to the 19th, or 524,288), he uses gradient accumulation. A bug he walks through in a small example: summed gradients are too large unless each loss is divided by the number of accumulation steps. He then moves to PyTorch's DistributedDataParallel on eight GPUs, which averages gradients across processes, and reaches about 1.5 million tokens per second.

FineWeb-Edu data, HellaSwag and the results

Tiny Shakespeare is replaced by a 10 billion token sample of FineWeb-Edu, a filtered Common Crawl subset. He contrasts it with GPT-2's WebText, built from Reddit outbound links. He adds a validation split and a HellaSwag evaluation, where the model must pick the likeliest of four endings. OpenAI's 124M model scores about 29.5 percent.

One epoch, about two hours, passes that score and beats OpenAI's checkpoint on validation loss. He cautions that the data differs and HellaSwag may have leaked into training data. A four-epoch overnight run on about 40 billion tokens nearly matches GPT-3 124M, which saw 300 billion tokens. The loss curve shows odd periodicity he attributes to unshuffled data, and torch.compile breaks sampling and evaluation in his code.

Plots of training and validation loss and HellaSwag accuracy, with horizontal reference lines for the OpenAI models.
Training curves from the overnight run, compared against OpenAI's GPT-2 and GPT-3 124M on HellaSwag.

He closes by showing his llm.c project, a C/CUDA version that reproduces the same losses and runs faster. The code is in his build-nanogpt repository.

Questions and answers

What did Andrej Karpathy publish in his June 2024 video Let's reproduce GPT-2 (124M)?

Andrej Karpathy published a nearly four-hour video on June 9, 2024, in which he rebuilds OpenAI's 124 million parameter GPT-2 model from scratch in PyTorch. He writes the network, speeds up training roughly elevenfold, and trains it on eight A100 GPUs. The code is in his build-nanogpt repository.

How did Andrej Karpathy make GPT-2 (124M) training 11x faster in 2024?

Andrej Karpathy cut step time on an A100 from about 1,000 ms to 90 ms through a series of changes. TF32 gave 333 ms, bfloat16 autocast 300 ms, torch.compile 130 ms, Flash Attention 96 ms, a vocabulary padded from 50257 to 50304 about 93 ms, and a fused AdamW optimizer 90 ms.

Did Karpathy's GPT-2 (124M) reproduction beat OpenAI's model on HellaSwag?

Yes. Andrej Karpathy's one epoch run on 10 billion FineWeb-Edu tokens, taking about two hours, passed OpenAI's GPT-2 124M checkpoint score of about 29.5 percent on HellaSwag. He cautions that the training data differs and HellaSwag may have leaked into the training data.

What hardware and training speed did Karpathy use to train GPT-2 (124M)?

Andrej Karpathy trained his GPT-2 (124M) reproduction on eight A100 GPUs using PyTorch's DistributedDataParallel, which averages gradients across processes. This setup reached about 1.5 million tokens per second. He used gradient accumulation to reach a batch of 524,288 tokens, matching the GPT-3 paper's batch of about half a million.

Which GPT-3 settings did Karpathy use when rebuilding GPT-2 (124M)?

Andrej Karpathy borrowed GPT-3's settings because that paper is described in more detail. These are AdamW betas of 0.9 and 0.95, gradient norm clipping at 1.0, weight decay of 0.1 on matrices and embeddings only, and a cosine learning rate schedule with warmup. He skipped the batch size ramp to keep the arithmetic simple.

How close did Karpathy's longer GPT-2 (124M) run get to GPT-3 124M?

Andrej Karpathy's four-epoch overnight run on about 40 billion tokens nearly matched the GPT-3 124M result. GPT-3 124M saw 300 billion tokens. He also shows his llm.c project, a C/CUDA version that reproduces the same losses and runs faster.

From the YouTube description

We reproduce the GPT-2 (124M) from scratch. This video covers the whole process: First we build the GPT-2 network, then we optimize its training to be really fast, then we set up the training run following the GPT-2 and GPT-3 paper and their hyperparameters, then we hit run, and come back the next morning to see our results, and enjoy some amusing model generations. Keep in mind that in some places this video builds on the knowledge from earlier videos in the Zero to Hero Playlist (see my channel). You could also see this video as building my nanoGPT repo, which by the end is about 90% similar.

Links:
- build-nanogpt GitHub repo, with all the changes in this video as individual commits: https://github.com/karpathy/build-nanogpt
- nanoGPT repo: https://github.com/karpathy/nanoGPT
- llm.c repo: https://github.com/karpathy/llm.c
- my website: https://karpathy.ai
- my twitter: https://twitter.com/karpathy
- our Discord channel: https://discord.gg/3zy8kqD9Cp

Supplementary links:
- Attention is All You Need paper: https://arxiv.org/abs/1706.03762
- OpenAI GPT-3 paper: https://arxiv.org/abs/2005.14165 - OpenAI GPT-2 paper: https://d4mucfpksywv.cloudfront.net/better-language-models/language_models_are_unsupervised_multitask_learners.pdf- The GPU I'm training the model on is from Lambda GPU Cloud, I think the best and easiest way to spin up an on-demand GPU instance in the cloud that you can ssh to: https://lambdalabs.com

Chapters:
00:00:00 intro: Let’s reproduce GPT-2 (124M)
00:03:39 exploring the GPT-2 (124M) OpenAI checkpoint
00:13:47 SECTION 1: implementing the GPT-2 nn.Module
00:28:08 loading the huggingface/GPT-2 parameters
00:31:00 implementing the forward pass to get logits
00:33:31 sampling init, prefix tokens, tokenization
00:37:02 sampling loop
00:41:47 sample, auto-detect the device
00:45:50 let’s train: data batches (B,T) → logits (B,T,C)
00:52:53 cross entropy loss
00:56:42 optimization loop: overfit a single batch
01:02:00 data loader lite
01:06:14 parameter sharing wte and lm_head
01:13:47 model initialization: std 0.02, residual init
01:22:18 SECTION 2: Let’s make it fast. GPUs, mixed precision, 1000ms
01:28:14 Tensor Cores, timing the code, TF32 precision, 333ms
01:39:38 float16, gradient scalers, bfloat16, 300ms
01:48:15 torch.compile, Python overhead, kernel fusion, 130ms
02:00:18 flash attention, 96ms
02:06:54 nice/ugly numbers. vocab size 50257 → 50304, 93ms
02:14:55 SECTION 3: hyperpamaters, AdamW, gradient clipping
02:21:06 learning rate scheduler: warmup + cosine decay
02:26:21 batch size schedule, weight decay, FusedAdamW, 90ms
02:34:09 gradient accumulation
02:46:52 distributed data parallel (DDP)
03:10:21 datasets used in GPT-2, GPT-3, FineWeb (EDU)
03:23:10 validation data split, validation loss, sampling revive
03:28:23 evaluation: HellaSwag, starting the run
03:43:05 SECTION 4: results in the morning! GPT-2, GPT-3 repro
03:56:21 shoutout to llm.c, equivalent but faster code in raw C/CUDA
03:59:39 summary, phew, build-nanogpt github repo

Corrections:
I will post all errata and followups to the build-nanogpt GitHub repo (link above)

SuperThanks:
I experimentally enabled them on my channel yesterday. Totally optional and only use if rich. All revenue goes to to supporting my work in AI + Education.

Watch on YouTube

Working out what this means for your business?

Aileron Shift builds the systems behind this site: AI newsrooms that research, write and publish on their own, marketing automation and WordPress hosting for companies that need to move faster than their competitors.