{"slug": "the-annotated-microgpt", "title": "The Annotated MicroGPT", "summary": "A new blog post, \"The annotated microGPT,\" walks through a 200-line character-level language model that trains on 32,033 first names from Andrej Karpathy's makemore dataset and prints 20 generated names in 37 seconds on an M4 MacBook Pro across 1,000 training steps. The author's implementation differs from Karpathy's in two ways: it runs the full sequence through gpt() at once instead of one token at a time with a KV cache, and it updates weights with plain SGD rather than Adam. The post argues the script shares the same underlying algorithm as ChatGPT, with only scale and engineering separating them.", "body_md": "[← blog](https://samitmohan.in/blog)\n\n# The annotated microGPT\n\nThe [previous post](https://samitmohan.in/blog/how-chatgpt-works) covered what happens when you press 'submit' on ChatGPT. This covers the code.\n\nChatGPT and the script below share the same algorithm. Scale and engineering differ; the math does not. ChatGPT runs on thousands of GPUs and trains on the internet. This script learns from a list of 32,033 names on your laptop: Karpathy's version runs 1,000 training steps, one name per step, and prints 20 names in 37 seconds on an M4 MacBook Pro.\n\nIt's 200 lines, the only imports are `os`, `math` and `random`, plus `urllib.request` once to download the names. My code differs from Karpathy's in 2 ways, because I wanted it to be from scratch:\n\n- It runs the full sequence through `gpt()` at once. Karpathy's`gpt()` takes one token at a time and keeps a[KV cache](https://samitmohan.in/blog/inference#5-the-kv-cache) .\n- It updates the weights with plain SGD. Karpathy's file uses [Adam](https://samitmohan.in/blog/interview-questions#adam-from-scratch) .\n\nActually these concepts are not that hard and the code is quite simple for them. You can read the original code [here](https://gist.github.com/karpathy/8627fe009c40f57531cb18360106ce95)\n\n*Prerequisites:* know what a gradient is. If not: read [neural networks](https://samitmohan.in/blog/nn), [the math](https://samitmohan.in/blog/math)\n\nA language model has one job. It predicts the next token from the context so far.\n\nBefore the code, click through each step of the forward pass. The widget uses a toy model: 8 words (\"the cat sat ...\"), 8-dimensional vectors, 2 heads, [LayerNorm](https://samitmohan.in/blog/math#layernorm) and GELU, a final LayerNorm, output weights tied to the embedding, and argmax. microGPT uses 27 characters, 16 dimensions, 4 heads, RMSNorm and ReLU, no final norm, a separate `lm_head`, and sampling. The other steps are the same.\n\n## 1. data (lines 1-27)\n\nThe dataset is 32,033 human first names from Karpathy's makemore project. Gippity uses byte pair encoding (BPE) as its [tokeniser](https://samitmohan.in/blog/how-chatgpt-works#tokenization). We use a character-level tokenizer instead: the alphabet maps to IDs 0-25, and one special token sits at ID 26: `BOS` (beginning of sequence). Vocab size = 27 (26 a-z + 1 BOS).\n\n`\"\".join(docs)` concatenates every name into one giant string. `set()` removes the duplicates, and `sorted()` sorts them.\n\n`BOS` marks both the beginning and the end of a name. One token is simpler than two separate tokens: `[BOS, c1, c2, ..., cn, BOS]`. When the model produces `BOS` during inference, generation stops (here `EOS` and `BOS` are the same).\n\nBOS doubling as EOS works because the model learns from examples: every name in the training data ends with BOS. After training, the model produces BOS to end a name.\n\nTokenization for \"emma\":\n\nTwo things here: inputs and targets. The inputs are every token except the last one. The targets are every token except the first one. The model sees the inputs `[:-1]` and must predict `[1:]`, the next token at each position. \"emma\" gives 5 training pairs:\n\nAt position t, the model sees tokens[0..t] and must predict tokens[t+1]\n\n## 2. autograd engine (lines 29-72)\n\nParameters are what you tune / nudge in the right direction. The parameters are the weights of the model (microGPT has no biases). Think of them as the connection strengths between the neurons in our brain. To make them learn the right things, we tune them as the model sees more and more data.\n\nWhat is the 'right' direction here? We check how each weight changes the loss: does a small increase in the weight increase or decrease the loss? To minimise the loss, we move each parameter in the negative direction of its gradient. Backpropagation computes these gradients with the [chain rule](https://samitmohan.in/blog/math#more-on-chain-rule). Entire of microgpt is just backpropagation with optimisations on top.\n\nGradient descent needs dLoss/d(every parameter). For 4,192 parameters, that's 4,192 derivatives per step. Autograd computes all of them. It records every operation in a graph during the forward pass, then walks the graph in reverse. The `Value` class below is a compact version of Karpathy's [micrograd](https://github.com/karpathy/micrograd) (PyTorch does the same thing on tensors, see [how PyTorch autograd works](https://samitmohan.in/blog/torch#autograd)).\n\n### the Value class\n\nEvery scalar is a `Value` node. It stores four things:\n\n- `data` : the scalar value, computed in the forward pass.\n- `grad` : the derivative of the loss with respect to this node.\n- `local_grads` : the derivative of this node with respect to each of its inputs.\n- `_children` : the inputs that produced this node. For c = a + b, the children of c are a and b.\n\nEach operation computes its local derivatives when it creates the node and stores them in the `local_grads` tuple. micrograd stores a `_backward` function on each node instead; microGPT stores plain numbers.\n\nPython \"dunder\" methods like `__add__` define what happens when you write `a + b`: Python calls `a.__add__(b)` under the hood.\n\nThe derivative tells you what a small nudge to the input does to the output. Does the output increase or decrease, and by how much?\n\nWe need this impact for every parameter with respect to the loss. Then we can change each parameter to make the loss smaller. This is backprop btw.\n\nThe local derivative of a sum with respect to each input is 1: a change in one input moves the sum by the same amount.\n\n`__radd__` and `__rmul__` are \"reflected\" operators. For `3 * v`, `int.__mul__` does not know the `Value` type, so Python calls `v.__rmul__(3)`. Without them, `3 * some_value` raises `TypeError`.\n\nThe `log` above adds `1e-10` to avoid `log(0)`. Karpathy's `log` (line 48) has no epsilon. His file also defines `__rsub__` and `__rtruediv__`.\n\n### backward()\n\nThis method goes inside the `Value` class: a topological sort, then one reverse pass of the chain rule, the same engine as [stackgrad's autograd](https://samitmohan.in/blog/minitorch#nineteen-operations) but on scalars.\n\n## 3. hyperparameters and weight init (lines 74-90)\n\nEach weight starts as a random sample from a Gaussian with standard deviation 0.08. Small weights keep the activations from exploding. If weights start large, each layer multiplies by a large number and the values grow, hence we start small, learn from there.\n\nThe full parameter list is below. `wte` holds one 16-dim row per token (27 rows), and `wpe` holds one 16-dim row per position (16 rows). `lm_head` turns the final 16-dim vector into 27 scores, one per token. Count them by hand:\n\nThe two embedding tables come first. The code stores the six matrices of the transformer block in lists, so each transformer block gets its own copy:\n\nThe code collects every parameter `Value` into one flat list, so the SGD loop can update all 4,192 parameters in a single pass:\n\nThis is what makes `for param in params: param.data -= lr * param.grad` in the training loop work (all parameters from all layers in one flat iterable).\n\nEmbeddings are vectors, not integer IDs, because vectors can capture similarity. Characters that play similar roles in names, like the vowels, can learn nearby vectors. An integer ID for 'a' (=0) has no geometric relationship to 'n' (=13). A learned 16-dim vector does.\n\n## 4. utility functions (lines 94-106)\n\n`linear` is a matrix-vector multiply. This is the forward pass of a single layer.\n\nLogits are unnormalized scores before softmax. A logit of 5.0 doesn't mean 'probability 5.0'. It means this token is more likely than one with logit 2.0. `softmax` turns logits into probabilities. It subtracts the max logit first, so `math.exp` cannot overflow: the [max_logit trick](https://samitmohan.in/blog/interview-questions#numerical-stability-the-max_logit-trick).\n\nAfter softmax, the output is a probability distribution: non-negative values that sum to 1. In `attention_block` (section 5) softmax turns raw dot-product scores into attention weights. In the training loop it turns the model's final logits into token probabilities.\n\n`rmsnorm` divides a vector of length  by its root-mean-square:\n\nNormalization keeps activations in a reasonable range. Nothing fancy here. The rewrite uses ; Karpathy's file uses (line 105).\n\n**Design choice:** RMSNorm instead of\n\n[LayerNorm](https://samitmohan.in/blog/math#layernorm). RMSNorm skips the mean subtraction. The RMSNorm paper and LLaMA keep a learned per-dimension scale; microGPT drops it, so this norm has no parameters.\n\n## 5. attention (lines 115-134)\n\n### the problem attention solves\n\nAn [MLP](https://samitmohan.in/blog/math#feed-forward-neural-network-ffn) (multi-layer perceptron) processes each position independently. Token at position 3 has no access to position 0. But predicting the 'a' in \"emm_\" is easier with the full context. Attention gives each token a channel to read from every past position. See [how attention works](https://samitmohan.in/blog/how-chatgpt-works#how-attention-works) for the high-level picture.\n\n### Q, K, V\n\nBefore computing Q, K, V, ask: who should each token pay attention to? A token representing 'm' in position 2 of 'emma' might attend to position 1 ('e') more than position 0 (BOS). Q, K, V give the model the machinery to figure that out from content.\n\nEach token projects its embedding through three learned matrices to produce three vectors:\n\n- **Q** (query): \"what am I looking for?\"\n- **K** (key): \"what do I advertise?\"\n- **V** (value): \"what do I carry?\"\n\nThe formula from [Attention Is All You Need](https://arxiv.org/abs/1706.03762), with  the length of one key vector (`head_dim` = 4 here):\n\nThe code below implements that formula, one scalar at a time.\n\n### causal masking\n\n`score(t, s) = dot(Q[t], K[s]) / sqrt(head_dim)`. Dot product measures alignment: if Q[t] and K[s] point in similar directions in 16-dimensional space, their dot product is large. Large score means high attention weight, which means s's value gets pulled into t's output. The model routes information based on what the query is asking and what the key is advertising.\n\nThe `sqrt(head_dim)` scaling keeps dot products from growing with the head dimension. If the entries of q and k have variance 1, their dot product has variance `head_dim`. At high dimension, a few scores dominate, softmax saturates (one weight goes to 1.0, rest go to 0), and gradients vanish. The scaling prevents this.\n\nWithout the causal mask every position can see all future tokens (the model learns to copy from the future rather than predict it; cheating)\n\nResult?\n\n**Cheating, measured.** The setup is a PyTorch copy of Karpathy's model: same shapes, Adam with β1 = 0.85 and β2 = 0.99, linear learning-rate decay, one name per step, 1,000 steps. Train it twice, with and without the causal mask, and test on 500 names it never trained on.\n\n- Training loss, mean of the last 100 steps: 2.28 with the mask, 0.035 without.\n- Held-out loss: 2.352 with the mask, 0.061 without.\n- Samples at T=0.5: names like \"anaya\" and \"rahan\" with the mask; 10 of 10 empty without it.\n\nCausal mask: the rewrite's loop runs `s in range(t+1)`, so future tokens never exist in the score list. No explicit mask matrix (just don't compute the scores). Karpathy's `gpt()` gets the same effect from the KV cache. It processes one position at a time, and `keys[li]` holds only the keys of the positions so far (lines 121-129).\n\nThis is O(T²) per head per layer. For T=16, the causal loop computes 1 + 2 + ... + 16 = 136 scores per head, 544 for 4 heads. Fine here. At T=100K (long-context models), a full T × T score matrix holds 10¹⁰ entries per head, 40 GB in fp32. [Flash attention](https://samitmohan.in/blog/inference#6-flashattention) avoids storing that matrix. It computes the scores in tiles, so memory grows with T, not T².\n\n### multi-head\n\nSplit Q, K, V into `n_head=4` slices of `head_dim=4` each. Run attention on each head separately. Heads can specialize: one might track character repetition (\"mm\" in \"emma\"), another common name endings, another positional distance. Training decides what each head tracks. Concatenate the 4 outputs back to 16 dims, then project through `wo`.\n\nThe output of each attention head is a weighted average of value vectors:\n\nAttention is just a learnable weighted sum.\n\n### the residual connection\n\nAfter attention: `x = x + attn_out`. This is a skip connection, the idea from [ResNet](https://samitmohan.in/blog/math#resnets--residual-networks). Without it, gradients multiply through every layer and shrink toward zero before they reach early parameters. With it, the gradient path from loss to input includes a direct addition. The derivative of `x + f(x)` w.r.t. `x` is `1 + df/dx`, so the gradient keeps a direct path with derivative 1, even if `f` learns nothing. See [attention-residuals](https://samitmohan.in/blog/attention-residuals).\n\nThe residual add happens in `gpt()` (section 7), not inside `attention_block`.\n\n**Checkpoint: attention.** Attention computes content-based weighted averages of value vectors. Multi-head runs this in parallel across different learned projections. Causal masking prevents looking at future tokens. The math is three linear projections (Q, K, V), a scaled dot product, a softmax, a weighted sum, and the output projection Wo.\n\n## 6. the MLP (lines 135-141)\n\nAttention mixes information across positions. MLP processes each position's vector independently. Expand 16 -> 64 (4x width), apply ReLU, project back 64 -> 16.\n\nThe logic is simple; more dimensions = more you know about the data (more capacity; intuitive when you think about any data and increase dimensions)\n\nMLP = per-token compute. Attention = cross-token communication. The transformer alternates between these two operations: attention lets tokens talk to each other, MLP lets each token process what it heard.\n\nIn larger models, research finds factual associations stored in the MLP layers ([Geva et al. 2021](https://arxiv.org/abs/2012.14913), [Meng et al. 2022](https://arxiv.org/abs/2202.05262)), things like 'anna' implies female name.\n\n**Design choice:** ReLU instead of GELU. GELU is smoother and used in GPT-2/GPT-3. ReLU is simpler and works fine here.\n\n## 7. the full forward pass (lines 108-144)\n\nPositional embeddings are not optional. Attention without a mask is permutation equivariant: shuffle the input tokens and the outputs shuffle the same way. Without position information, 'emma' and 'mame' would give the same set of vectors. The causal mask breaks part of this symmetry, but `wpe` gives the model the position directly, so it can distinguish position 0 from position 3. The original transformer uses fixed sin/cos [positional encodings](https://samitmohan.in/blog/math#positional-encoding) instead of a learned table.\n\nKarpathy's `gpt()` also applies `rmsnorm` once to the embedding sum, before the first block (line 112). The rewrite below skips that step.\n\nShape walkthrough for input \"em\" (BOS plus 2 letters, e=4, m=12):\n\nEach token and its position each contribute a learned 16-dim vector. The code adds the two vectors element by element.\n\nThe result is the model's complete representation of \"this token at this position.\"\n\nPre-norm puts RMSNorm before each sub-layer; post-norm puts it after. Pre-norm keeps the residual stream unmodified by the norm. The original Transformer used post-norm. GPT-2 moved the norm to the input of each sub-block, and LLaMA kept pre-norm with RMSNorm.\n\nThe model is differentiable. Every operation (embeddings, attention scores, softmax, weighted sum, MLP, final projection) is composed of Value nodes. loss.backward() computes dLoss/d(every weight) in one pass.\n\n## 8. training loop (lines 146-184)\n\n### loss: cross-entropy\n\nCross-entropy loss = -log(p[target]).\n\nIf the model assigns 90% probability to the correct token: loss = -log(0.9) = 0.11.\n\nIf it assigns 1%: loss = -log(0.01) = 4.6.\n\nThe log function penalizes confident wrong answers harshly: as p goes to 0, the loss goes to infinity. A confident correct answer (p near 1) costs almost nothing.\n\nWhy log? Cross-entropy is the negative log-likelihood of the data under the model. The log turns products of probabilities into sums, which are numerically stable and easier to differentiate.\n\n### backward + SGD\n\nGradients accumulate by += in backward(). If you skip the zero step, the step-2 update uses the gradients of step 1 plus step 2, the step-3 update uses all three, and so on. Old gradients keep pushing the weights, the updates grow, and training can diverge. Zero every step.\n\n**Surprise:** this is vanilla SGD, not Adam. Three lines: subtract gradient, zero gradient, move on. Adam keeps a moving average of each parameter's gradient (momentum) and of its square (variance). That is two extra buffers, each as long as the parameter list. Karpathy's file uses Adam with β1 = 0.85, β2 = 0.99, bias correction and a linear learning-rate decay (lines 146-149 and 174-182). See\n\n[Adam from scratch](https://samitmohan.in/blog/interview-questions#adam-from-scratch)and the\n\n[Adam paper](https://arxiv.org/abs/1412.6980).\n\nLoss starts at ~3.3 (-log(1/27) ≈ 3.3, random model with 27 classes). The model sees 160 names (20 steps × 8 batch). With the settings above, plain SGD barely moves the loss: it stays between 3.28 and 3.31 for all 20 steps. The sampled names are still random letters, like \"pvgysrdmxzqtpabt\" and \"nndxlt\".\n\nKarpathy's script trains with Adam on one name per step, for 1,000 steps:\n\nEach step's loss comes from a single name, so it jumps around. The average over 50 steps tells the real story: 2.85 for steps 1-50, 2.32 for steps 951-1000.\n\nWhat does pure Python cost? On an M4 MacBook Pro, Karpathy's script (CPython 3.14) takes 37 s for the 1,000 steps plus the 20 samples, about 37 ms per step. The same model in PyTorch 2.14 on the M4 CPU (same shapes, Adam, one name per step) takes 0.40 ms per step. That is about 90× faster for the same math. Karpathy's docstring says it: \"Everything else is just efficiency.\"\n\n**Checkpoint: training.** Forward pass computes loss. backward() fills every param.grad. SGD subtracts lr*grad. grad=0 resets for next step. This is the complete training algorithm.\n\n## 9. inference (lines 186-200)\n\nStart from `[BOS]`. Run the full forward pass. Take logits at the last position. Apply temperature. Softmax. Sample. Append. Repeat until BOS comes back out. The rewrite reruns `gpt()` on the whole context for every new token. Karpathy's loop feeds one token per call and reuses the KV cache (lines 189-199).\n\nThat's all autoregressive generation is: run the model, get probabilities over next tokens, pick one, condition on it, repeat. The model never \"sees\" what it's about to generate: it only sees what it has generated so far.\n\nTemperature is `logit / T` before softmax. If the model's top logit is 2.0 and second is 1.5:\n\n- T=0.5: logits become 4.0 and 3.0. The gap widens, and the top token dominates.\n- T=1.0: unchanged\n- T=2.0: logits become 1.0 and 0.75. The gap narrows, and the distribution gets more even.\n\nTemperature controls the entropy of the output distribution ([temperature](https://samitmohan.in/blog/how-chatgpt-works#temperature) in the ChatGPT post).\n\n- T → 0 approaches argmax (always pick the most likely token, no diversity). The code divides by T, so T=0 itself raises `ZeroDivisionError` .\n- T=1 samples from the raw model distribution\n- T>1 flattens the distribution (more surprising outputs)\n\nSampling instead of argmax gives diversity: two runs with the same context produce different names. This is why when you enter the same prompt more than once in chatgpt; you get different results.\n\nAttention weights depend on the content of Q and K. Apart from the causal mask, position information enters only through the initial wpe embeddings. Once inside the transformer, everything is content-based.\n\n`random.choices` samples one item from `range(vocab_size)`, weighted by probability, so tokens with a higher probability get picked more often. It returns a list, hence the `[0]`.\n\nKarpathy's script prints these 20 samples after its 1,000 Adam steps (seed 42, T=0.5):\n\nThe model trained on 1,000 names, and none of these 20 samples is one of them. It learns the pattern (vowel/consonant rhythm, common endings like -a, -an, -ina) from examples in 1000 steps.\n\nTemperature decides how close the samples stay to real names. Rerun the same trained model with seed 42 and count the samples that are real names somewhere in the 32,033-name dataset:\n\n- T=0.5: 11 of 20 (\"anna\", \"lara\", \"anton\")\n- T=1.0: 3 of 20\n- T=1.5: 0 of 20, and some are unpronounceable, like \"hisvnof\" and \"nchhry\"\n\n## 10. from microgpt to chatgpt\n\nOpenAI has not published the size of the ChatGPT models. The right column uses GPT-3, the model family behind the first ChatGPT, from the [GPT-3 paper](https://arxiv.org/abs/2005.14165).\n\n| microGPT | GPT-3 / ChatGPT | \n|---|---|\n| 32K names | 300B training tokens (GPT-3) | \n| 4,192 params, 1 layer | 175B params, 96 layers | \n| Adam + linear LR decay (Karpathy), SGD (the rewrite) | Adam + LR warmup and cosine decay + grad clipping | \n| no post-training | SFT + RLHF (ChatGPT) | \n\nSame algorithm. Scale and engineering differ. The tokenizer, the serving stack and the rest of the gap are in [how ChatGPT works](https://samitmohan.in/blog/how-chatgpt-works).\n\nThe scaled dot-product attention formula comes from the Attention paper (2017), and it hasn't changed. Later models changed parts around it: pre-norm, RMSNorm, rotary position embeddings, grouped-query attention. Most of the other changes from 2017 to GPT-4 are in the data pipeline, post-training (SFT + RLHF), infra and [compute budget](https://samitmohan.in/blog/scalinglaws#flops).\n\n## references\n\n- [Karpathy's microgpt.py](https://gist.github.com/karpathy/8627fe009c40f57531cb18360106ce95) and[his blog post about it](https://karpathy.github.io/2026/02/12/microgpt/)\n- [Karpathy's makemore](https://github.com/karpathy/makemore) : the dataset and spirit\n- [Andrej Karpathy: The spelled-out intro to language modeling](https://www.youtube.com/watch?v=PaCmpygFfXo)\n- [Jay Alammar: The Illustrated Transformer](https://jalammar.github.io/illustrated-transformer/)\n- [Jay Alammar: The Illustrated GPT-2](https://jalammar.github.io/illustrated-gpt2/)\n- Vaswani et al. (2017): [Attention Is All You Need](https://arxiv.org/abs/1706.03762)", "url": "https://wpnews.pro/news/the-annotated-microgpt", "canonical_source": "https://samitmohan.in/blog/microgpt", "published_at": "2026-12-01 00:34:27+00:00", "updated_at": "2026-12-01 01:15:56.598961+00:00", "lang": "en", "topics": ["artificial-intelligence", "machine-learning", "large-language-models", "neural-networks", "ai-research"], "entities": ["microGPT", "ChatGPT", "Andrej Karpathy", "makemore", "M4 MacBook Pro"], "also_reported_by": [], "takeaway": "A 200-line character-level GPT with a 27-token vocab (26 letters plus BOS, which doubles as EOS), 16 dimensions and 4 heads trains on 32,033 names in 1,000 SGD steps and generates 20 names in 37 seconds on an M4 MacBook Pro.", "recommendation": {"advice": "Train a from-scratch character-level GPT on a small name corpus with plain SGD and a single BOS token doubling as EOS to learn the full forward and backward pass end to end.", "playbook": "training-data", "playbook_url": "https://wpnews.pro/playbooks/training-data"}, "alternates": {"html": "https://wpnews.pro/news/the-annotated-microgpt", "markdown": "https://wpnews.pro/news/the-annotated-microgpt.md", "text": "https://wpnews.pro/news/the-annotated-microgpt.txt", "jsonld": "https://wpnews.pro/news/the-annotated-microgpt.jsonld"}}