Let's build GPT: from scratch, in code, spelled out.
Overview
Andrej Karpathy builds a decoder-only GPT in PyTorch from an empty file, training a character-level model on roughly one million Tiny Shakespeare characters and explaining each step from tokenization and batching to causal self-attention, multi-head blocks, residual connections, layer normalization, and dropout. The resulting model has about 10 million parameters and reaches a validation loss near 1.48; Karpathy then connects the implementation to nanoGPT and explains how large-scale pretraining differs from the supervised fine-tuning and preference-optimization stages used to make ChatGPT an assistant.
Key takeaways
- A character-level GPT can be built from a 65-character vocabulary, next-character targets, causal self-attention, and a standard PyTorch training loop.
- Causal attention is a weighted communication system: query-key dot products choose which past positions matter, while value vectors carry the information that gets aggregated.
- Multi-head attention gives each token several parallel channels for gathering context, and feed-forward layers then process that gathered information independently at each position.
- Residual connections and pre-norm layer normalization make deeper Transformer stacks easier to optimize by preserving gradient paths and stabilizing token representations.
- Karpathy's approximately 10-million-parameter model reaches validation loss near 1.48 on Tiny Shakespeare, while GPT-3's largest model used 175 billion parameters and about 300 billion training tokens.
- Pretraining creates a document completer, not automatically an assistant; assistant demonstrations, human preference rankings, a reward model, and PPO can further align responses.
Chapters
- ChatGPT generates text sequentially and can produce different completions for the same prompt.
- Karpathy defines a language model as a system that learns which characters, words, or tokens tend to follow a given sequence.
- The build will focus on the Transformer architecture from the 2017 paper Attention Is All You Need, not a production-scale ChatGPT replica.
- The training corpus is Tiny Shakespeare, roughly 1 MB of text used to teach a character-level model Shakespeare-like patterns.
- Karpathy introduces nanoGPT, a compact repository with separate model and training code, and proposes rebuilding its core from scratch.
- The project assumes Python, basic calculus and statistics, and familiarity with PyTorch and the makemore language-modeling framework.
- A character tokenizer maps each distinct character to an integer and uses a reverse lookup to decode generated integers back into text.
- Tiny Shakespeare contains 65 unique characters, making its vocabulary simple but its encoded sequences long.
- GPT-2's byte-pair encoding vocabulary has about 50,000 tokens, illustrating the tradeoff between vocabulary size and sequence length.
- The integer-encoded corpus is split into 90% training data and 10% validation data to monitor generalization and overfitting.
- A block size of 8 uses a nine-character slice to form eight next-character prediction examples, with targets offset from inputs by one.
- A batch size of 4 stacks independent sequences into a 4-by-8 tensor, allowing PyTorch and GPUs to process multiple examples in parallel.
- Karpathy implements a bigram language model with a token embedding table of shape vocabulary size by vocabulary size.
- Each character predicts the next character using only its own identity, with no access to earlier context.
- PyTorch cross-entropy evaluates predictions after reshaping logits from batch-by-time-by-channel into a two-dimensional array.
- The generation loop converts logits for the latest time step into probabilities with softmax, then samples with torch.multinomial.
- Each sampled character is concatenated to the existing context, extending the sequence one token at a time.
- The initial bigram model produces mostly random-looking text because its parameters have not yet been trained.
- Karpathy trains with the AdamW optimizer, samples batches, computes cross-entropy, clears gradients, backpropagates, and updates parameters.
- Increasing training from 100 steps to 10,000 steps lowers the loss to about 2.5 and improves generated text.
- The bigram baseline remains limited because each prediction depends only on the immediately preceding character.
- The starter script adds CUDA device support so data and model parameters can run on a GPU.
- An evaluation function averages loss across multiple batches for both training and validation data, reducing the noise of single-batch measurements.
- model.eval(), model.train(), and torch.no_grad() handle evaluation behavior and avoid storing gradients when no backpropagation is needed.
- Karpathy demonstrates a simple causal aggregation rule: each token averages its own feature vector with all preceding vectors.
- A lower-triangular matrix prevents a position from receiving information from future tokens.
- The averaging is initially implemented with loops, then reformulated as batched matrix multiplication for efficiency.
- A lower-triangular matrix of weights can compute all prefix averages in parallel when each row is normalized to sum to one.
- Applying softmax to zeros and negative infinity produces the same causal averaging pattern while providing a path to learned, data-dependent weights.
- Karpathy adds 32-dimensional token embeddings and learned position embeddings so the model can represent both character identity and sequence location.
- Each token projects its representation into a query, meaning what it seeks, and a key, meaning what it contains.
- Query-key dot products produce attention scores that determine how strongly one position uses information from earlier positions.
- A triangular causal mask blocks future positions, and softmax turns the remaining scores into normalized aggregation weights.
- A value projection defines the information each token contributes when another token attends to it.
- Attention aggregates weighted value vectors across a directed graph of positions, with causal language modeling allowing each token to read itself and earlier tokens.
- Self-attention draws queries, keys, and values from the same input, while cross-attention can use keys and values from a separate encoded source.
- The Attention Is All You Need formulation scales query-key scores by one over the square root of the key dimension.
- Without scaling, dot-product variance grows with head size, which can make softmax overly sharp and concentrate attention on one position.
- Keeping scores moderate at initialization makes attention weights more diffuse and stabilizes learning.
- Karpathy implements a Head module with bias-free linear projections for keys, queries, and values.
- The head computes batched query-key scores, scales them, applies a registered lower-triangular buffer, and uses softmax to weight values.
- Generation crops the input context to block size so positional embeddings never receive positions beyond their table.
- Multi-head attention applies several self-attention heads in parallel and concatenates their outputs along the channel dimension.
- With a 32-dimensional embedding and four heads, each head has an 8-dimensional output, preserving the overall 32-channel size.
- The validation loss improves from about 2.4 to 2.28 after adding multiple attention heads.
- A feed-forward module applies a linear layer and ReLU independently to each token after attention.
- Attention gathers context between tokens; the feed-forward network lets each token process the information it gathered.
- Adding this computation lowers validation loss to about 2.24 in the small model.
- A Transformer block alternates multi-head self-attention with a feed-forward network.
- Residual connections add each module's output back to its input, creating a direct path through deeper networks for forward activations and gradients.
- Karpathy expands the feed-forward hidden dimension to four times the embedding size, following the Transformer design.
- Layer normalization normalizes features within each token, unlike batch normalization, which normalizes across examples.
- The implementation uses the pre-norm formulation, applying layer normalization before attention and feed-forward transformations.
- Adding normalization lowers validation loss slightly, from about 2.08 to 2.06, and a final layer norm precedes vocabulary prediction.
- The larger model uses a batch size of 64, a context block size of 256, and an embedding dimension of 384.
- Six attention heads each have 64 dimensions, and six Transformer layers are trained with dropout set to 0.2.
- After roughly 15 minutes on an NVIDIA A100 GPU, the approximately 10-million-parameter model reaches validation loss near 1.48 and generates 10,000 characters of Shakespeare-like text.
- The Shakespeare model is decoder-only because it generates text autoregressively and has no separate input source to encode.
- The original Attention Is All You Need architecture includes an encoder and cross-attention for tasks such as translating a French sentence into English.
- A decoder's triangular mask prevents future tokens from revealing targets during next-token prediction.
- nanoGPT separates training boilerplate in train.py from the Transformer definition in model.py.
- Its causal self-attention is mathematically equivalent but processes heads together using a four-dimensional tensor rather than a Python list of separate heads.
- The repository adds practical features such as checkpoint loading, learning-rate decay, model compilation, distributed training, and GPT-2-compatible GELU.
- Pretraining teaches a decoder-only Transformer to complete internet text; it does not by itself make the model a helpful question-answering assistant.
- GPT-3's largest model has 175 billion parameters and was trained on about 300 billion tokens, compared with Karpathy's roughly 10-million-parameter Shakespeare model.
- ChatGPT-style alignment adds assistant demonstrations, human rankings used to train a reward model, and PPO reinforcement learning to favor higher-reward responses.
- The roughly 200-line implementation reproduces the core decoder-only Transformer language-modeling process on Tiny Shakespeare.
- Large GPT models retain a closely related architecture but require vastly more parameters, data, and GPU infrastructure.
- The exercise covers pretraining, not the additional supervised or preference-based fine-tuning needed for task following and alignment.
Transcript excerpt
0:00 hi everyone so by now you have probably heard of chat GPT it has taken the world and AI Community by storm and it is a system that allows you to interact with an AI and give it text based tasks so for example we can ask chat GPT to write us a small Hau about how important it is that people understand Ai and then they can use it to improve the world and make it more prosperous so when we run this AI knowledge brings prosperity for all to see Embrace its power okay not bad and so you could see that chpt went from left to right and generated all these words SE sort of sequentially now I asked it already the exact same prompt a little bit earlier and it generated a slightly different outcome ai's power to grow ignorance holds us back learn Prosperity weights so uh pretty good in both cases and
0:49 slightly different so you can see that chat GPT is a probabilistic system and for any one prompt it can give us multiple answers sort of uh replying to it now this is just one example of a problem people have come up with many many examples and there are entire websites that index interactions with chpt and so many of them are quite humorous explain HTML to me like I'm a dog uh write release notes for chess 2 write a note about Elon Musk buying a Twitter and so on so as an example uh please write a breaking news article about a leaf falling from a tree uh and a shocking turn of events a leaf has fallen from a tree in the local park Witnesses report that the leaf which was previously attached to a branch of a tree attached itself and
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.