← all video summaries
Andrej Karpathy

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

Karpathy takes a blank file and builds a character-level GPT — complete with self-attention, multi-head mechanisms, residual connections, and layer normalization — then trains it on Shakespeare. Every architectural choice is explained through live code in Google Colab.

Watch on YouTube
TL;DR

What you'll learn

  1. The Transformer is a sequence-completion engine: given tokens, predict the next one, repeat.
  2. Self-attention lets every token query its past via learned affinities — queries, keys, and values.
  3. Multi-head attention gives parallel communication channels; residual connections + LayerNorm make deep networks trainable.
  4. nanoGPT (two files, ~200 lines each) reproduces the core of GPT-2's architecture.
  5. GPT-3 uses the same decoder-only blueprint, scaled to 175B params and 300B training tokens.

01 · The promise

ChatGPT's probabilistic magic

ChatGPT isn't deterministic — it's a language model that models the sequence of characters (or tokens) and completes whatever you give it. Run the same prompt twice and you get slightly different outputs. That randomness is the point: the model has learned the statistics of language and samples from them.

ChatGPT's interface showing four text-generation demos side by side.00:00:06
It models the sequence of words or characters — it knows how words follow each other in the English language.— Karpathy
Key insightGPT = Generative Pre-trained Transformer. The Transformer is the neural architecture; "generative pre-trained" describes the two-stage training pipeline.

02 · The architecture

"Attention Is All You Need"

The Transformer architecture emerged in 2017 as a machine translation paper nobody fully anticipated. Its core innovation: replace recurrence with attention. All you need is the attention mechanism — hence the title.

The "Attention Is All You Need" paper with its encoder-decoder architecture diagram.00:02:20
The authors didn't fully anticipate the impact that the Transformer would have on the field. This architecture, with minor changes, was copy-pasted into a huge amount of applications in AI.— Karpathy

03 · nanoGPT

From scratch, in code, spelled out

nanoGPT is Karpathy's minimalist implementation: two Python files of roughly 300 lines each. One defines the GPT model (the Transformer). The other trains it on any given text dataset. Starting with tiny Shakespeare (~1 MB of text), the goal is character-level generation — one character at a time.

The nanoGPT GitHub README showing the loss curve and example Shakespeare-like output.01:46:33
The numbersThe final model has ~10 million parameters, trained on ~300K tokens (tiny Shakespeare). The training code is roughly 200 lines.

04 · Tokenization

From characters to integers

Before the model sees any text, it must be converted to integers. Character-level tokenization maps each unique character to an index — Karpathy's tiny Shakespeare dataset has 65 possible characters (spaces, newlines, uppercase, lowercase, punctuation). This is the simplest possible tokenizer, but it produces very long sequences. Real models like GPT use subword tokenizers (byte-pair encoding via tiktoken) with a vocabulary of ~50K tokens, producing shorter sequences at the cost of a larger codebook.

Google Colab notebook showing the character vocabulary and encoding/decoding functions.00:08:40
You can trade off the codebook size and the sequence lengths: very long sequences of integers with very small vocabularies, or short sequences with very large vocabularies.— Karpathy

05 · Training data

Batches, blocks, and context

The model never sees the full text at once. Instead, it trains on random chunks (blocks) of fixed length — Karpathy starts with block size 8, then scales to 256. Each block contains multiple training examples: given the first N characters, predict the (N+1)th. A batch stacks B independent blocks, processed in parallel on the GPU.

Colab output showing the training data tensor — a 4×8 matrix of integer sequences with their corresponding targets.01:02:30
Training setupFinal configuration: batch size 64, block size 256, learning rate 3e-4, 6 attention heads, 6 layers, 384-dim embeddings, 0.2 dropout. Trained on an A100 GPU for ~15 minutes. Validation loss dropped from 4.87 (random) to 1.48.
We're never going to actually feed the entire text into a Transformer all at once — that would be computationally very expensive and prohibitive.— Karpathy

06 · Self-attention

Tokens that talk to each other

In a character-level model, tokens don't inherently communicate. Self-attention fixes this: every token emits a query (what am I looking for?), a key (what do I contain?), and a value (what information will I share?). Queries dot-product with keys to produce affinities — learned attention weights — which softmax-normalize into a probability distribution over the past. The model then aggregates values weighted by these affinities.

The decoder architecture diagram showing self-attention blocks, feed-forward networks, LayerNorm, and the autoregressive masking.01:24:27
Attention is a communication mechanism — you can think about it as a communication mechanism where you have a number of nodes in a directed graph, and nodes aggregate information via a weighted sum from all the nodes that point to them.— Karpathy
Q · K — dot product between queries and transposed keys produces raw affinity scores

/ √d_k — scale by the square root of the head dimension to prevent softmax from becoming too peaky

softmax — normalize affinities into a probability distribution (with causal masking so future tokens can't attend)

· V — weighted aggregate of value vectors, producing the attended output

07 · Multi-head attention

Parallel communication channels

Instead of one monolithic attention mechanism, multi-head attention runs multiple heads in parallel — each with its own learned projections for Q, K, and V. The heads operate in lower-dimensional subspaces (e.g., 384-dim embeddings / 6 heads = 64-dim per head) and their outputs are concatenated. This lets different heads attend to different kinds of relationships: one might track subject-verb agreement, another might track long-range dependencies.

The transformer block implementation showing the multi-head attention module, feed-forward network, and residual connections.01:28:00
It's really just multiple attentions running in parallel and concatenating their results.— Karpathy

08 · The transformer block

Communication + computation

Each transformer block interleaves two operations: communication (multi-head self-attention) and computation (a position-wise feed-forward network). The feed-forward layer expands the embedding dimension by 4×, applies a ReLU (or GELU in nanoGPT), then projects back. Crucially, both operations use residual connections — the output of each sub-layer is added back to its input. This creates a "gradient super highway" that lets supervision flow unimpeded through deep networks.

Layer normalization normalizes the features at each token position (across the embedding dimension), stabilizing training. Karpathy uses the pre-normalization variant (LayerNorm before each sub-layer) rather than the original paper's post-normalization.

The scaling comparison from the Attention Is All You Need paper showing encoder and decoder blocks.01:39:00
Residual connectionsFrom the ResNet paper (2015): addition distributes gradients equally to both branches during backpropagation, so supervision hops through every addition node all the way to the input — an unimpeded gradient super highway.

09 · Scaling up

From Shakespeare to the internet

With residual connections and LayerNorm in place, the network becomes trainable at scale. Karpathy increases the model size: 384-dim embeddings, 6 heads, 6 layers, 64 batch size, 256 block size. The validation loss drops from 4.87 → 2.08 → 1.48. The generated text starts to resemble Shakespeare's register — archaic vocabulary and meter — even though it's nonsense.

The same architecture scales to GPT-3: 175 billion parameters (17,500× larger), trained on 300 billion tokens (~1M× more data), across thousands of GPUs. The architecture is "nearly identical" — just bigger.

GPT-3 model specifications table showing parameter counts, layer counts, and training token counts across model sizes.01:52:00
Between 10,000 and 1 million times bigger depending on how you count. That's all I have for now — go forth and transform.— Karpathy

10 · Beyond pre-training

Fine-tuning for conversation

Pre-training alone gives a document completer — not a chatbot. It completes whatever text you feed it, whether it's a question, a news article, or Shakespeare. To get ChatGPT's behavior requires two additional stages:

  1. Supervised fine-tuning: Train on human-written Q&A pairs so the model learns to expect a question and produce an answer.
  2. Reinforcement learning from human feedback (RLHF): Humans rank model responses; a reward model is trained on those rankings; PPO (policy gradient optimization) fine-tunes the model to maximize reward.
The full pipelinePre-training → document completer → SFT → assistant behavior → RLHF → aligned assistant (ChatGPT)
nanoGPT focuses on the pre-training stage. If you want the model to perform tasks, be aligned in a specific way, or detect sentiment — anytime you don't want just a document completer — you have to complete further stages of fine-tuning.— Karpathy