Skip to content

Karpathy: Let's build GPT, from scratch, in code, spelled out

Skip →RoPE (RoFormer)
main track #3corefundamentalvideorubric 12/122023 · ~150 min

Andrej Karpathy

Status

TL;DR. A coding lecture from January 2023 in the Neural Networks: Zero to Hero series. Karpathy builds a GPT in PyTorch on Tiny Shakespeare (about 1.1M characters, 65 distinct characters). He starts from a bigram model. Then he derives self-attention as a learned weighted average of past tokens and grows it into a full Transformer block. The final model has about 10.8M parameters. The code is in ng-video-lecture, and a cleaner version is nanoGPT. Watch the video.

Why it matters now. Every shape and mask in a modern LLM appears here in about 200 lines. It is the fastest way to turn the attention equation into working, debuggable code.

Self-attention is a data-dependent weighted average over the past. For head size hsh_s:

wei=softmax⁡ ⁣(mask⁡ ⁣(QK⊤hs)),out=wei V,\text{wei}=\operatorname{softmax}\!\left(\operatorname{mask}\!\left(\frac{QK^\top}{\sqrt{h_s}}\right)\right),\qquad \text{out}=\text{wei}\,V,

where the mask sets future positions to −∞-\infty. Each block then applies, with layer norm before each sub-layer:

x←x+MHA⁡(LN⁡(x)),x←x+FFN⁡(LN⁡(x)).x \leftarrow x+\operatorname{MHA}(\operatorname{LN}(x)),\qquad x \leftarrow x+\operatorname{FFN}(\operatorname{LN}(x)).

Lecture map (chapter times from the video description):

timechapterstudy page
9:28character tokenisation, train/val splitBPE for the subword version
22:11bigram baseline, loss, generation—
42:13–1:11:38four versions of self-attentionAttention Is All You Need
1:00:18positional encodingRoPE
1:16:56why divide by √head_sizeAttention Is All You Need
1:21:59multi-head attentionGQA for shared key and value heads
1:26:48–1:32:51residual connections, layer normIllustrated Transformer
1:42:39encoder vs decoder vs bothBERT, T5
1:48:53ChatGPT, GPT-3, pre-training vs fine-tuning, RLHFGPT-3, PPO, Karpathy deep dive
Let's build GPT: from averaging the past to self-attention, then to a full Transformer block Top row: four versions of the same idea, each shown as a 4 by 4 weight matrix over positions where only the lower triangle is non-zero. Version 1 averages previous tokens with for loops. Version 2 does the same with a matrix multiply by a lower-triangular matrix whose rows sum to one. Version 3 fills the upper triangle with minus infinity and applies softmax, giving the same uniform weights. Version 4 makes the weights data-dependent: softmax of queries times keys divided by the square root of the head size, so each row has different weights. Bottom: the block is then built step by step, adding multi-head attention, a feed-forward layer, residual connections, layer norm, and finally scale and dropout. The final model has 6 layers, 6 heads, width 384, a context of 256 characters, a vocabulary of 65 characters and about 10.8 million parameters. 1. One weighted average, four implementations v1 · for loops 42:13 mean of x_1..x_t v2 · matmul 51:54 tril / row sums v3 · softmax 54:42 0 0 0 0 0 0 mask −inf, softmax v4 · Q, K, V 1:02:00 0 0 0 0 0 0 softmax(QKᵀ/√hs) Rows: query positions; columns: past positions. v1–v3 weights are equal; v4 learns them. 2. Grow it into a Transformer block multi-head1:21:59 feed-forward1:24:25 residual1:26:48 layer norm1:32:51 scale + dropout1:37:49 Final model: 6 layers × 6 heads, width 384, context 256 characters, dropout 0.2, vocabulary 65. About 10.8M parameters, trained on 1.1M characters of Tiny Shakespeare (90% train, 10% val).
Original sketch. Top: the lecture's four implementations of causal averaging, ending in learned query-key weights. Bottom: the order in which the Transformer block is assembled, with chapter times, and the final model's size.

The lecture’s final gpt.py uses batch size 64, context 256, width 384, 6 heads, 6 layers, dropout 0.2, learning rate 3e-4 and 5,000 steps. My count of its parameters is 10,788,929. Samples look like Shakespeare in form but not in sense. nanoGPT ships a similar character-level config (256 context, 384 channels, 6 layers, 6 heads). Its README reports about 3 minutes on one A100 and a best validation loss of 1.4697.

  • Character level, tiny data. No subword tokeniser and only 1M characters, so it overfits quickly and its results do not tell you much about scaling.
  • Two corrections are listed in the description. The most important is to scale by head size, not width.
  • No weight initialisation. The repo README says this was skipped, which slows convergence.
  • Old block design. Learned absolute positions, LayerNorm and a ReLU MLP, where current models use RoPE, RMSNorm and gated MLPs (see the architecture comparison).
  • Unanswered by design. The four exercises (batched heads, own dataset or addition, pre-train then fine-tune, add a feature from a paper) are left to you.

Questions to think through

These questions have no single right answer. Write or say your answer before you open the hints. Mark a question once you could defend your answer in a reading group.

  1. Derive / compute

    The final model has vocabulary 65, context 256, width 384, 6 layers, 6 heads and a 4× feed-forward. Using the code (query, key and value without bias; other linear layers with bias; two layer norms per block and one at the end), count its parameters and check the total of 10,788,929.

    What a strong answer covers
    • Token and position embeddings: 65 × 384 + 256 × 384 = 24,960 + 98,304 = 123,264.
    • Per block: Q, K, V 3 × 384² = 442,368; output projection 384² + 384 = 147,840; feed-forward 384 × 1536 + 1536 + 1536 × 384 + 384 = 1,181,568; two layer norms 1,536. Total 1,773,312.
    • Six blocks: 10,639,872. Final layer norm 768 and output head 384 × 65 + 65 = 25,025.
    • Sum: 123,264 + 10,639,872 + 768 + 25,025 = 10,788,929. The feed-forward layers hold about two thirds of the weights.
  2. Mechanism

    The lecture reaches self-attention in four versions: for loops, a matrix multiply, a masked softmax, and query-key scores. Explain what each step adds, why the upper triangle is filled with minus infinity rather than zero, and why position embeddings are then needed.

    What a strong answer covers
    • v1 averages each token with its past, a weak but correct causal aggregation.
    • v2 does the same as one batched matrix multiply with a lower-triangular matrix whose rows sum to one.
    • v3 fills future positions with minus infinity and applies softmax. exp(−∞) = 0 gives exactly zero weight, and rows still sum to one; zeros before the softmax would give e^0 = 1 and leak the future.
    • v4 replaces the uniform scores with q · k / √head_size, so weights depend on content.
    • Attention acts on a set and ignores order, so a learned position embedding is added to the token embedding.
  3. Critique

    The video description lists two corrections: at 57:00 it should say tokens from the future cannot communicate, and at 1:20:05 the scores should be scaled by head_size, not C. Explain the impact of the second bug in the final model and what the repository README says is still missing.

    What a strong answer covers
    • With C = 384 and head_size = 64, scaling by 1/√384 instead of 1/√64 makes scores √6 ≈ 2.4 times too small.
    • Softmax is then flatter, especially at initialisation, so heads start closer to uniform averaging and may learn sharp patterns more slowly; it is a rescaling, so training can partly compensate through the weights.
    • The published gpt.py uses k.shape[-1] ** −0.5, the head size.
    • The README notes the lecture skipped weight initialisation, so the code converges more slowly than nanoGPT, which has a dedicated init function.
  4. What if…

    The block is built in steps: multi-head attention, feed-forward, residual connections, layer norm, then scale and dropout. Design an ablation that removes each piece from the final model, and predict what you would see and why.

    What a strong answer covers
    • Hold data, steps, learning rate and seed fixed; report validation loss and training curves for each variant, with several seeds.
    • Without residual connections the 6-layer model should be much harder to optimise, since gradients must pass through every sub-layer.
    • Without layer norm (applied before each sub-layer here) training should be less stable, especially at higher learning rates.
    • Removing the position embedding makes the model order-blind apart from the causal mask, which should hurt a character model.
    • Without dropout the 10.8M-parameter model should overfit 1M characters faster, widening the train-val gap.
  5. Design

    Exercise 2 suggests training the GPT to add two numbers. Design the data, targets and evaluation, following the hints in the video description, and explain why reversing the answer digits should help.

    What a strong answer covers
    • Generate random problems such as 123+456= on the fly instead of a fixed text file, with separate held-out pairs and longer numbers for testing.
    • Mask the loss on the problem tokens (target −1 with ignore_index) so the model is trained only on the answer.
    • Write the answer digits in reverse, so the model emits the lowest digit first, as the carry algorithm does, and each digit depends only on digits already seen.
    • Measure exact-match accuracy by number length, including lengths longer than training, to test whether it learned an algorithm.
  6. Connect

    Exercise 3 asks whether pre-training on a large corpus and then fine-tuning on Tiny Shakespeare lowers validation loss. Relate this to GPT-3 and to the ChatGPT discussion at the end of the video.

    What a strong answer covers
    • The lecture model is only the pre-training stage: a document completer trained on one small corpus.
    • Pre-training on a large corpus gives general statistics; fine-tuning with a lower learning rate adapts them, which should beat training from scratch on 1M characters.
    • GPT-3 is the same decoder-only design at far larger scale, with BPE tokens instead of characters.
    • ChatGPT adds further fine-tuning stages (supervised and RLHF) on top of a pre-trained model to make it an assistant.

Done with this page?

Status