How GPT Works — v2
How a language model learns from a name, then writes one of its own.
Supporting evidence for Passing It On: an illustrated explanation and the experiments behind it.
Ask a chatbot “Who wrote Wuthering Heights?” and it will probably answer “Emily Brontë.” When you hit Send, the chat app passes your question to a language model. The text the model receives is called the prompt.
Your request goes out. The reply comes back.
Who wrote
Wuthering Heights?
Adds instructions
and chat history
Generates
the reply
Read the answer
Shows the reply
Emily Brontë
The reply grows one piece at a time.
The model doesn’t write the whole answer at once. It scores what could come next, software picks one piece, adds it, and asks again. Those pieces are called tokens: a word, part of a word, or punctuation.
Each new token is added to the text, and the model scores again.
Who wrote Wuthering Heights?
Reply: …
Reply: Emily
The longer text goes back in. Next the model scores what follows “Emily”, and so on until it picks a stop token.
Where do those scores come from? Training. To watch it happen, we’ll switch to a tiny model that can’t answer questions at all. It only continues names, one letter at a time, which makes each prediction small enough to follow.
Take the name Emma and cover the last two letters. What comes after em? If you were thinking of Emma, you’d say m. If you were thinking of Emily, you’d say i. Both fit. So what would it mean for a model to get the answer wrong?
Andrej Karpathy’s microgpt learns from names one character at a time. Given the letters so far, it assigns probabilities to the possible next characters. What happens to those probabilities depends on whether the program is learning from a name or writing one.
The name supplies the letter.
emmemma supplies the target m. The program scores its probability; it needn’t draw a letter.
Training updates the weights after scoring the name.
Software draws the letter.
emiSoftware draws i from the probabilities, then feeds emi back in. There’s no target to check.
Generation keeps the weights fixed.
i and a were the trained model’s two most likely letters after “em”, at about 22% each.While writing a new name, the model draws an unlikely letter. Does that surprise cause it to adjust its weights?
See the answer
No. The letter changes what comes next because it becomes part of the name so far. The weights stay fixed. During training there was an observed next letter to score; during generation there’s only the continuation the program drew.
Inside the model: from “em” to a set of scores
So far the model has been a box that turns “the text so far” into a probability for each possible next token. Here is what happens inside that box in microgpt. Every number in this section comes from a run we recorded: Karpathy’s file, unmodified, trained for its default 1,000 steps (about two minutes on a laptop CPU). The model has 4,192 weights. Each one is an ordinary decimal number, set randomly at the start and adjusted during training.
The model reads one token at a time. Its vocabulary has 27 tokens: the 26 letters plus a special marker, written here as ·, that means “start of a name” when it comes first and “end of the name” when the model predicts it. To score what follows “em”, the model processes ·, then e, then m, and the scores it produces at m are its prediction.
1. Each letter becomes a point in space
A letter means nothing to arithmetic, so the first step replaces each token with a list of 16 numbers, its embedding. You can think of the list as coordinates: each letter is a point in a 16-dimensional space. We can’t draw 16 dimensions, but we can measure relationships in them. The most useful measure is direction. Two letters whose arrows from the origin point the same way tend to be treated similarly by the rest of the model, though the position information added next and the later weights can still pull them apart.
Nobody tells the model which letters are alike. It starts with random embeddings and moves them whenever moving them would have improved a prediction. After 1,000 names, something recognizable appears:
After training, the vowels have drifted together.
y in amber, m circled. Measured in all 16 dimensions, the average similarity between two vowels went from −0.01 before training to 0.53 after; between a vowel and a consonant, from 0.00 to −0.29. Similarity here is cosine similarity: 1 means the same direction, 0 unrelated, −1 opposite. The model was never told what a vowel is.Vowels often occupy similar roles in names, so the clustering is consistent with the model learning those roles. Similar embedding directions can let later weights treat tokens alike, but this observation does not establish that clustering caused better predictions. Large models use the same general idea of learned coordinates, with thousands of dimensions rather than 16.
Position matters as well. An a at the start of a name behaves differently from one at the end. So the model also keeps a second table of 16-number lists, one for each of the 16 positions a name can occupy, and adds the position’s list to the letter’s. The sum, rescaled to a standard size, is the model’s starting description of “this letter, here.”
Show me the code
tok_emb = state_dict['wte'][token_id] # 27 tokens × 16 numbers
pos_emb = state_dict['wpe'][pos_id] # 16 positions × 16 numbers
x = [t + p for t, p in zip(tok_emb, pos_emb)]
x = rmsnorm(x) # rescale to a standard sizermsnorm divides the list by its root-mean-square, so no single position or letter starts out shouting louder than the rest. It appears several more times inside the model for the same reason.
2. Attention: each position looks back
The embedding for m says nothing about what came before it. But what follows m depends a lot on whether the name so far is “em”, “am”, or “mm”. Attention is the step where each position gathers information from the earlier ones.
From its current description, each position computes three new lists of numbers using three tables of weights:
- a query: roughly, what this position is looking for;
- a key: what this position offers to positions that come later;
- a value: the information it hands over if someone attends to it.
The current position compares its query with the key of every position so far, including itself. A comparison is a dot product: multiply the two lists number by number and add the results. Matching directions give a large score. The scores are turned into weights that add up to 1, using the same softmax step that turns the final scores into probabilities. The position then takes a weighted average of the values. It can only look backward. That matters in training: when the model predicts what follows “em”, the answer is sitting in the training name, and looking ahead would let it copy instead of predict.
microgpt does this four times in parallel, with each head using its own quarter of the numbers, so different heads can look for different things. Here are all four heads at the first m in “emma”: the position that predicts what follows “em”.
The same first m mixes earlier information differently in each head.
| Head | Start · | e | First m |
|---|---|---|---|
| 1 | 0.430 | 0.346 | 0.224 |
| 2 | 0.415 | 0.299 | 0.286 |
| 3 | 0.392 | 0.566 | 0.043 |
| 4 | 0.274 | 0.459 | 0.267 |
0.392 × value(·) + 0.566 × value(e) + 0.043 × value(m). These coefficients mix value vectors; they are not contributions to the final letter probability.Optional evidence: all attention rows for “emma”
At the first m, where the model predicts what follows “em”, head 3 looks mostly at the e.
m: its output becomes the scores for the next letter. There, head 3 puts 0.57 of its weight on the e; the other heads spread theirs across the start marker, e and m. In a model this small, heads rarely have tidy, nameable jobs, so treat these as what one trained model did, not as rules.The four heads’ outputs are joined back into one list of 16, passed through one more table of weights, and added to the position’s description rather than replacing it. That addition, called a residual connection, means attention contributes extra information on top of what the position already knew.
Show me the arithmetic
Each head works with 4 of the 16 numbers. Its score for an earlier position is (q · k) / √4; dividing by the square root of the list length keeps the scores from growing just because lists are longer. Softmax turns the scores into weights. The output is the weighted sum of the values.
attn_logits = [dot(q_h, k_h[t]) / head_dim**0.5 for t in range(len(k_h))]
attn_weights = softmax(attn_logits)
head_out = [sum(attn_weights[t] * v_h[t][j] for t in ...) for j in range(head_dim)]3. The MLP: working with what it gathered
Attention moves information between positions. The next step works on each position separately. It expands the 16 numbers to 64 using one table of weights, sets every negative result to zero, and compresses back to 16 with another table. Setting negatives to zero, called ReLU, is what lets this step act like a set of 64 switches, each one turning on only for certain combinations of inputs. Without that bend, two tables in a row would collapse into one and could only compute simple weighted sums. The result is again added to the position’s description.
Large models stack dozens of these attention-plus-MLP layers, each one refining the description passed up from the last. microgpt has one.
4. Scores, then probabilities
Finally, a last table of weights turns the position’s 16-number description into 27 scores, one per token. Softmax converts them to probabilities: raise e to each score, then divide by the total, so every result is positive and they add to 1. Here is what the trained model predicts after “em”, next to what actually follows “em” in the full list of names:
The trained model favors a vowel after “em”, but the names more often double the m.
The model has learned something real: a consonant is usually followed by a vowel, and it gives vowels (counting y) 80% of its probability after “em”, up from 26% before training. But it gives m only 1%, though nearly 30% of “em” names continue with a second m. The training section returns to this mismatch.
Where the 4,192 weights are
| Letter embeddings | 27 × 16 | 432 |
| Position embeddings | 16 × 16 | 256 |
| Attention: query, key, value, output | 4 × (16 × 16) | 1,024 |
| MLP: expand, compress | 2 × (16 × 64) | 2,048 |
| Final scores | 27 × 16 | 432 |
| Total | 4,192 |
Counted from the running model, not estimated.
How training changes the weights
Scoring a prediction
Training shows the model one name per step. At every position it asks for the model’s probability of the letter that actually comes next, including the end marker, and charges a penalty called loss: the negative logarithm of that probability. A confident correct prediction costs almost nothing. A probability of 1% costs 4.6. The baseline worth remembering is a model that spreads its probability evenly over all 27 tokens: it pays log 27, or 3.30, at every position. The penalties for one name are averaged into a single number for that step.
For “emma”, our trained model would pay about 3.0 for the opening e (it gives names starting with e a 5% chance), then 4.6 for the second m, the letter it underrates.
Finding which way to move 4,192 numbers
The loss is the end of a long chain of arithmetic. Nearly all of the 4,192 weights feed into it on every step; the exceptions are embedding rows for letters and positions that this particular name doesn’t use, which get a gradient of zero. Training needs to know, for each weight, whether nudging it up would raise or lower the loss, and by how much. That number is the weight’s gradient.
microgpt records every addition and multiplication as it computes the loss, building a graph of every small operation for that name. It then walks the graph backward from the loss. At each operation it knows a simple local fact: for a multiplication a × b, a small change in a changes the result by b times as much. Multiplying these local factors along every path from a weight to the loss, and adding the paths together, gives that weight’s gradient. This is the chain rule from calculus, applied mechanically, and it is called backpropagation.
Then every weight takes a small step meant to lower the loss. Computing gradients tells us how the loss responds; an update rule called Adam uses them to choose the changes. A single step can still make one name’s loss worse; what training lowers is the trend.
Optional: Adam settings and training code
microgpt uses an update rule called Adam, which keeps a running average of each weight’s recent gradients and their sizes, so weights with consistent, small gradients still move and weights with noisy, large ones don’t lurch. The step size starts at 0.01 and shrinks steadily to nearly zero by the last step.
loss = (1 / n) * sum(losses) # average penalty over the name
loss.backward() # chain rule, back through the graph
for i, p in enumerate(params): # Adam update for every weight
m[i] = beta1 * m[i] + (1 - beta1) * p.grad
v[i] = beta2 * v[i] + (1 - beta2) * p.grad ** 2
p.data -= lr_t * m_hat / (v_hat ** 0.5 + eps_adam)What 1,000 steps bought
Loss starts at the level of an even guess and falls to about 2.3.
The names the model writes show the same progress more vividly. These were generated at four points in the same run, with the same random seed each time so the difference comes from the weights:
| Step | Invented names |
|---|---|
| 0 | jdodmicpalbdjxcj, pzol, bwhechtepsnqbdeq |
| 50 | janalee, aicai, den |
| 200 | hananna, amalene, jona |
| 1,000 | caran, ananan, nail |
Generated with temperature 0.5, which sharpens the probabilities before each draw so the model sticks closer to its favorites. None of these is checked against the training list; some could be real names.
At step 0 the model types noise. By step 50 it has the rhythm of consonants and vowels. By step 1,000 the samples are more name-like and heavy on a and n, two of the three most common letters in the list.
What it didn’t learn
Back to the second m. Before training, the model gave it 2.7% after “em”. After training, 1%. The data says nearly 30%. Training made this particular prediction worse.
Training lowers average loss, not every continuation. This run saw only 996 distinct names, including 6 beginning “emm”; limited exposure is one possible explanation, not a demonstrated cause.
The same 4,192-weight architecture, retrained on 90% of the names for 20 passes, gave the second m 22–24%. It can learn substantially more of the exception without growing. But batching and scheduling changed along with data exposure: this demonstrates capacity under another regimen, not that data alone caused the recovery. The optional experimental extension contains the longer-run investigation and shared methods.
Same operations, larger models
The steps on this page are the steps inside the large models too: tokens become vectors, attention lets each position look back at earlier ones, MLPs work on each position, a final layer produces a score per token, and training lowers the average of −log p using gradients from backpropagation and an update rule. microgpt is a simplified copy of the GPT-2 design. GPT-3’s authors say they “use the same model and architecture as GPT-2”, with one stated exception in how attention is laid out across layers, and trained it with Adam, as microgpt does (Brown et al., 2020). Karpathy’s simplifications are small ones: microgpt uses a simpler rescaling step, a simpler bend in the MLP, and leaves out a few added constants that GPT-2 and GPT-3 include. The lists and tables grow, and training processes much more text.
| microgpt | GPT-3 175B | |
|---|---|---|
| Tokens | 27: letters and an end marker | word pieces from a learned vocabulary (GPT-2’s byte-level tokenizer) |
| Numbers per token (embedding width) | 16 | 12,288 |
| Attention-plus-MLP layers | 1 | 96 |
| Context: how far back it can look | 16 tokens | 2,048 tokens |
| Weights (parameters) | 4,192 | 175 billion |
| Training-data exposure | 7,170 predicted letters and end markers, over 1,000 names | 300 billion tokens |
| Llama 3.1 405B: further scale | 405 billion weights; about 15 trillion pretraining tokens; up to 128,000 tokens of context | |
GPT-3 figures from Table 2.1 and Section 2 of Brown et al. Llama 3.1 figures are reported by Meta (paper abstract, model card). We omit models whose makers have not published their sizes. Tokens differ between models, so exposure counts are not a count of equivalent pieces of text.
In our five-size names experiment, continued training of the larger models improved training fit while worsening loss on validation names. That is stronger evidence of overfitting than generated names matching a training list. The validation set also selected learning rates and checkpoints, so it is not an untouched test. This is one small dataset and regimen, not a scaling law.
The useful claim is narrow. If you followed this page, you know the kinds of arithmetic GPT-3 performs to produce a token, and with its weights, its code, and enormous patience you could trace them. That is not the same as knowing why its 175 billion weights produce a good answer. In microgpt we could check one thing the weights had learned, that vowels cluster, because there are only 27 tokens and 16 dimensions to look at. Working out what large models have learned, and where in their weights it lives, is an active research field called interpretability, and it is far from finished.
Scale also changes what the same operations can do. Our name models are trained only to continue names, not to answer questions. GPT-3’s authors reported that making models larger “greatly improves task-agnostic, few-shot performance”: the bigger models got much better at doing a new task after seeing a few examples of it in the prompt, without any extra training (Brown et al.). Nothing in the steps above predicts that, which is part of why it was a notable result.
What turns a predictor into an assistant
A model trained only to continue text continues text. Ask it a question and it might answer, or it might write three more questions in the same style, because both are plausible continuations. Chatbot models get further training after this stage, usually called post-training. In one common recipe, people write example replies for the model to imitate (supervised fine-tuning), then rank the model’s own replies so it can be trained toward the ones people prefer (reinforcement learning from human feedback, or RLHF). Meta describes using both for the tuned Llama 3.1 models (model card). It can matter more than size: in OpenAI’s InstructGPT study, people rating replies to the prompts in that study preferred a 1.3-billion-weight model trained this way to the 175-billion-weight GPT-3 (Ouyang et al., 2022). Post-training uses the same loss-gradient-update machinery as this page; what changes is the data and how “better” is scored.
Back at the opening exchange, the app supplies your question, instructions and chat history as context. The post-trained model scores continuations suited to answering; software selects tokens and returns the reply through the app. Context changes this request, while training changes the weights used across requests. The same machinery can produce “Emily Brontë”—but token probabilities are not truth confidence, and neither the forward pass nor post-training alone explains when a factual answer is reliable.
Optional experimental extension: longer training, same-size recovery and size sweep
What the names experiments establish
From 1,000 to 10,000 steps, then full-list retraining
Average loss need not improve every continuation. Training lowers the average loss over the names it sees, and a few facts make “emm” a poor bet for this run. In 1,000 steps the model sees 996 different names, about 3% of the 32,033 in the file. Only 15 of those begin with “em”, and 6 of those continue with m. Meanwhile it sees thousands of cases where a consonant is followed by a vowel. One possible reading is that limited evidence about “em” lets a broad consonant–vowel pattern dominate. Our first reading was that it simply hadn’t seen enough evidence. So we tested it: we trained a second copy from the same starting weights for 10,000 steps instead of 1,000. That run sees 9,723 different names, 103 beginning with “em”, 27 of those continuing with m.
Ten times the training moved it the right way, to 6%, but it was still far from the data. That left open whether more exposure would be enough, or whether this architecture could learn the exception under a different regimen.
We then tested whether this same architecture could learn the exception under a different training regimen. We rebuilt microgpt’s exact design in PyTorch, checked that it computes the same scores as Karpathy’s code when given the same weights, and trained the same 4,192-weight size on a GPU from Kaggle’s free notebook service. This time it saw 90% of all 32,033 names (the other 10% served as validation for choosing learning rates and checkpoints), 20 times over. Three runs with different random starting weights gave the second m 22%, 24% and 24%.
The tiny architecture has capacity to learn much more of the exception. More data exposure, batching and scheduling changed together, so this does not isolate data as the cause of recovery. In its 1,000 steps it met 6 names starting “emm”. The full training list in our larger runs has 78. It still lands about six points short of the data’s 30%; three runs aren’t enough to say whether that gap means anything.
The PyTorch runs follow microgpt’s design but not its exact training: they process 64 names at a time instead of one, and each size gets the learning rate that worked best for it. The shared sweep methods follow.
Complete checkpoint specimens from the original run
| Step | Invented names |
|---|---|
| 0 | jdodmicpalbdjxcj, pzol, bwhechtepsnqbdeq, liomhsugpozri, ckufnbqwpykuntmx, zlscuq, wgjtalfccsefixbm, ovsyhikyzeeegnsk |
| 50 | janalee, aicai, den, meyaten, jiimin, bainen, jarian, tii |
| 200 | hananna, amalene, jona, arelan, briinan, kenenn, kaney, eyan |
| 1,000 | caran, ananan, nail, kaya, alan, anelia, analir, mamil |
We tried scaling it up ourselves
To see what size changes in a setting we could watch, we trained microgpt’s design at five sizes, from its own 4,192 weights to 6.3 million, a 1,500-fold range. Each size got wider vectors and more layers; every one trained on the same 28,830 names for up to 20 passes. We used 3,203 validation names, absent from gradient updates, to select the best checkpoint; the same set selected each size’s learning rate. It was not an untouched test. Each size ran three times.
Validation gains flattened as size grew on this fixed dataset.
| Weights | Width × layers | Best pass (of 20) | Sample of generated names |
|---|---|---|---|
| 4,192 | 16 × 1 | 20 | dani, adayla, ellis, ritzee, denari, manasim |
| 26,816 | 32 × 2 | 20 | danill, adalee, ellish, river, delani, madis |
| 201,088 | 64 × 4 | 17–20 | danilla, adalee, eliyah, riverlee, demarius, manasima |
| 1,188,608 | 128 × 6 | 7–10 | danil, adalee, elinor, river, daren, manas |
| 6,309,376 | 256 × 8 | 8–10 | danil, adalee, ellisa, river, delayla, janneet |
Two things happen as the model grows. Up to about 200,000 weights, the loss on unseen names falls clearly: more numbers let the model capture more of what makes a name sound like a name. Past that it barely moves: 1.97, 1.96, 1.96. The largest models also hit their best result early, after 7 to 10 passes rather than 20, and if training continued, they got worse on the unseen names while getting better on the ones they had seen. The share of generated names matching the training list also tends to rise with size: about half for the smallest model, 70 to 80 percent for the three largest.
The training–validation divergence is evidence of overfitting on this fixed dataset; it does not isolate how much extra data would help. The training names add up to about 205,000 letters per pass. The larger models have enough weights to fit the particular names in the list more closely than the general patterns justify, which helps on names they’ve seen and hurts on names they haven’t. Name matches, especially at temperature 0.5, do not by themselves show that a model memorized a particular example.
Two Tesla T4 GPUs were available, but the script used a single CUDA device without distributed training. The fifteen retained runs plus learning-rate trials took 38.5 minutes overall. Bigger models start from smaller random weights, scaled to their width, and each size used the best of three learning rates. One small sweep on one dataset: it shows the pattern, not a law for how large models scale.
Selection and reproducibility
The PyTorch forward pass matched the pure-Python transcription on identical weights to a maximum absolute score difference of 1.1102230246251565e-16. Each size tried learning rates 0.001, 0.003 and 0.01 at seed 0; the lowest validation loss selected the rate. That rate then ran at seeds 1 and 2. Every run selected its best epoch on the same validation set. There was no separate test set. Training used batches of 64, Adam and linear learning-rate decay; initialization scaled with width. These changes prevent an isolated data-versus-size causal conclusion.
Optional technical notes: tokenizers, sampling and speed
Technical notes
- Building the vocabulary. Word-piece tokenizers are learned from text before training starts, by repeatedly merging pairs of symbols that often appear next to each other into new tokens; GPT-2 and GPT-3 start from bytes rather than letters. Common words end up as a single token, while rare ones are split into several, sometimes down to individual characters.
- Temperature and sampling settings. The invented names above were drawn at temperature 0.5. microgpt divides every score by the temperature before softmax, so values below 1 widen the gaps between scores and the draws stick closer to the favorites. Chat apps choose settings like this, and some add rules such as drawing only from the most likely few tokens.
- Everything around the model. The chat app’s hidden instructions, memory of past chats, web search and other tools all work by adding text to the prompt or acting on text the model writes. They live in the app, not in the weights.
- Making it fast. Training at GPT-3’s scale means splitting the model across many GPUs and processing many sequences at once. microgpt does one name at a time in plain Python, which is what makes it readable and also what makes it hopeless at scale.
Additional architecture details
| microgpt | GPT-3 175B | |
|---|---|---|
| Attention heads per layer | 4, of 4 numbers each | 96, of 128 numbers each |
| MLP expansion | 16 → 64 → 16 | 12,288 → 49,152 → 12,288 |
Some details have also been refined along the way. One example: every Llama 3.1 model uses grouped-query attention, in which several attention heads share the same keys and values so the model is cheaper to run (model card). Changes like this alter how the steps are computed, not what the steps are.