Skip to content
← writing

The annotated microGPT

Apr 2, 2026 · 26 min read · llm, from-scratch

contents
  1. 1. data (lines 1-27)
  2. 2. autograd engine (lines 29-72)
  3. 3. hyperparameters and weight init (lines 74-90)
  4. 4. utility functions (lines 94-106)
  5. 5. attention (lines 115-134)
  6. 6. the MLP (lines 135-141)
  7. 7. the full forward pass (lines 108-144)
  8. 8. training loop (lines 146-184)
  9. 9. inference (lines 186-200)
  10. 10. from microgpt to chatgpt
  11. references

The previous post covered what happens when you press 'submit' on ChatGPT. This covers the code.

ChatGPT 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 trains on 32,033 names on your laptop: Karpathy's version runs 1,000 training steps and prints 20 names in 37 seconds on an M4 MacBook Pro.

It'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:

  • It runs the full sequence through gpt() at once. Karpathy's gpt() takes one token at a time and keeps a KV cache.
  • It updates the weights with plain SGD. Karpathy's file uses Adam.

Actually these concepts are not that hard and the code is quite simple for them. You can read the original code here

Prerequisites: know what a gradient is. If not: read neural networks, the math

A language model has one job. It predicts the next token from the context so far.

Before 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 and GELU. microGPT uses 27 characters, 16 dimensions, 4 heads, RMSNorm and ReLU. The steps are the same.


1. data (lines 1-27)

The dataset is 32,033 human first names from Karpathy's makemore project. Gippity uses byte pair encoding (BPE) as its tokeniser. 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).

python
import urllib.request, os
 
url = "https://raw.githubusercontent.com/karpathy/makemore/master/names.txt"
if not os.path.exists("names.txt"):
    urllib.request.urlretrieve(url, "names.txt")
docs = open("names.txt").read().splitlines()  # list of 32,033 names
 
chars = sorted(set("".join(docs))) # ['a','b',...,'z'] - 26 chars
BOS = len(chars) # ID 26
vocab_size = len(chars) + 1 # 27

"".join(docs) concatenates every name into one giant string. set() removes the duplicates, and sorted() sorts them.

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).

BOS 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.

Tokenization for "emma":

▶
26 (BOS)
e
4
m
12
m
12
a
0
▶
26 (BOS)
Each character maps to an integer ID. BOS wraps the sequence.

Two 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:

input context target ▶ e (predict 'e' from BOS) ▶ e m (predict 'm' from BOS,e) ▶ e m m (predict 'm' from BOS,e,m) ▶ e m m a (predict 'a' from BOS,e,m,m) ▶ e m m a ▶ (predict BOS = end)
Each row is one training pair. Context grows left to right. Target (orange) is the next token.
python
doc = "emma"
char_tokens = []
for c in doc:
    char_tokens.append(chars.index(c))
tokens = [BOS] + char_tokens + [BOS] # tokens = [26, 4, 12, 12, 0, 26]
 
input_tokens  = tokens[:-1]  # [26, 4, 12, 12, 0]
target_tokens = tokens[1:]   # [4, 12, 12, 0, 26]

At position t, the model sees tokens[0..t] and must predict tokens[t+1]


2. autograd engine (lines 29-72)

Parameters 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.

What 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. Entire of microgpt is just backpropagation with optimisations on top.

Gradient 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 (PyTorch does the same thing on tensors, see how PyTorch autograd works).

the Value class

Every scalar is a Value node. It stores four things:

  • data: the scalar value, computed in the forward pass.
  • grad: the derivative of the loss with respect to this node.
  • local_grads: the derivative of this node with respect to each of its inputs.
  • _children: the inputs that produced this node. For c = a + b, the children of c are a and b.
Value data = 6.0 grad = 0.0 local_grads = (b, a) a = 2.0 child[0] b = 3.0 child[1] local_grad=b=3 local_grad=a=2
For a=2, b=3, out=a*b=6. local_grads store d(out)/d(a)=b=3 and d(out)/d(b)=a=2.

Each 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.

Python "dunder" methods like __add__ define what happens when you write a + b: Python calls a.__add__(b) under the hood.

The derivative tells you what a small nudge hh to the input does to the output. Does the output increase or decrease, and by how much?

dfdx=lim⁡h→0f(x+h)−f(x)h\frac{df}{dx} = \lim_{h \to 0} \frac{f(x+h) - f(x)}{h}

We 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.

python
class Value:
    def __init__(self, data, _children=(), local_grads=()):
        self.data = data
        self.grad = 0 # dLoss/d(this) - general gradient or derivative, this gets updated when you call .backward()
        self._children = _children # tuple of Value nodes that produced this node
        self.local_grads = local_grads # d(this)/d(each child) 
 
    # d(a+b)/da = 1, d(a+b)/db = 1
    def __add__(self, other):
        other = other if isinstance(other, Value) else Value(other)
        out = Value(self.data + other.data, _children=(self, other))
        out.local_grads = (1.0, 1.0) # d(a+b)/da = da/da = 1
        return out
 
    # d(a*b)/da = b, d(a*b)/db = a
    def __mul__(self, other):
        other = other if isinstance(other, Value) else Value(other)
        out = Value(self.data * other.data, _children=(self, other))
        out.local_grads = (other.data, self.data)  # cross-multiply
        return out
 
    # d(x^n)/dx = n * x^(n-1)
    def __pow__(self, other):
        return Value(self.data**other, (self,), (other * self.data**(other-1),))
 
    # d(log x)/dx = 1/x
    def log(self):
        return Value(math.log(self.data + 1e-10), (self,), (1/(self.data + 1e-10),))
 
    # d(exp x)/dx = exp(x)
    def exp(self):
        return Value(math.exp(self.data), (self,), (math.exp(self.data),))
 
    # d(relu x)/dx = 1 if x>0, else 0
    def relu(self):
        return Value(max(0, self.data), (self,), (float(self.data > 0),))
 
    def __neg__(self):   return self * -1
    def __sub__(self, other): return self + (-other)
    def __truediv__(self, other): return self * other**-1
 
    def __radd__(self, other): return self + other
    def __rmul__(self, other): return self * other

The local derivative of a sum with respect to each input is 1: a change in one input moves the sum by the same amount.

__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.

The log above adds 1e-10 to avoid log(0). Karpathy's log (line 48) has no epsilon. His file also defines __rsub__ and __rtruediv__.

backward()

This method goes inside the Value class: a topological sort, then one reverse pass of the chain rule, the same engine as stackgrad's autograd but on scalars.

a = 2.0 grad = 0 → grad = 3 b = 3.0 grad = 0 → grad = 2 c = 1.0 grad = 0 → grad = 1 a*b = 6.0 grad = 0 → 1 loss = a*b+c = 7 grad = 1 (seed) 1*3=3 1*2=2 1*1=1 1*1=1 green = forward orange = backward gradient flow
loss = a*b + c = 7. Forward pass builds values (green). Backward seeds grad=1 at loss, then chain-rule propagates to a (grad=3), b (grad=2), c (grad=1).
python
def backward(self):
    topological_graph = []
    visited = set()
 
    def build_top(v):
        if v not in visited:
            visited.add(v)
            for child in v._children:
                build_top(child)          # recurse into children first
            topological_graph.append(v)  # append AFTER children = post-order
 
    build_top(self)
    self.grad = 1                          # dLoss/dLoss = 1
    for v in reversed(topological_graph): # process root before leaves
        for child, local_grad in zip(v._children, v.local_grads):
            child.grad += local_grad * v.grad  # chain rule

3. hyperparameters and weight init (lines 74-90)

python
n_embed = 16    # every vector in the model has this length
n_head  = 4     # attention heads (each sees head_dim=4 dimensions)
n_layer = 1     # one transformer block
block_size = 16 # max sequence length
head_dim = n_embed // n_head  # = 4

Each 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.

python
def matrix(rows, cols):
    # Small Gaussian init (sigma=0.08) prevents activation explosion
    result = []
    for r in range(rows):
        row = []
        for c in range(cols):
            row.append(Value(random.gauss(0, 0.08)))
        result.append(row)
    return result

The 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:

wte:  27⋅16=432wpe:  16⋅16=256lm_head:  27⋅16=432attention:  4⋅162=1024MLP:  2⋅64⋅16=2048total=4192\begin{aligned} \texttt{wte}: \; 27 \cdot 16 &= 432 \\ \texttt{wpe}: \; 16 \cdot 16 &= 256 \\ \texttt{lm\_head}: \; 27 \cdot 16 &= 432 \\ \text{attention}: \; 4 \cdot 16^2 &= 1024 \\ \text{MLP}: \; 2 \cdot 64 \cdot 16 &= 2048 \\ \text{total} &= 4192 \end{aligned}
4,192 total parameters wte 432 (27×16) wpe 256 (16×16) wq+wk+wv+wo 1024 (4×16×16) w_fc1 1024 (64×16) w_fc2 1024 (16×64) lm_head 432 (27×16) embeddings attention MLP output head
MLP and attention each hold 1024 params. Embeddings and output head mirror each other at 432 each.

The 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:

python
wte = matrix(vocab_size, n_embed)                # 27 x 16, token embeddings
wpe = matrix(block_size, n_embed)                # 16 x 16, position embeddings
 
wq   = []
wk   = []
wv   = []
wo   = []
w_fc1 = []
w_fc2 = []
 
for i in range(n_layer):
    wq.append(matrix(n_embed, n_embed))          # 16 x 16
    wk.append(matrix(n_embed, n_embed))          # 16 x 16
    wv.append(matrix(n_embed, n_embed))          # 16 x 16
    wo.append(matrix(n_embed, n_embed))          # 16 x 16
    w_fc1.append(matrix(n_embed * 4, n_embed))   # 64 x 16 (rows = output dim, cols = input dim)
    w_fc2.append(matrix(n_embed, n_embed * 4))   # 16 x 64
 
lm_head = matrix(vocab_size, n_embed)            # 27 x 16

The code collects every parameter Value into one flat list, so the SGD loop can update all 4,192 parameters in a single pass:

python
def flatten(mat):
    result = []
    for row in mat:
        for val in row:
            result.append(val)
    return result
 
params = flatten(wte) + flatten(wpe)
for i in range(n_layer):
    params += flatten(wq[i]) + flatten(wk[i]) + flatten(wv[i]) + flatten(wo[i])
    params += flatten(w_fc1[i]) + flatten(w_fc2[i])
params += flatten(lm_head)
 
print(f"num params: {len(params)}")   # 4192

This 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).

Embeddings 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.


4. utility functions (lines 94-106)

linear is a matrix-vector multiply. This is the forward pass of a single layer.

python
def linear(x, w):
    # output[i] = dot(w[i], x) for each row of the weight matrix
    result = []
    for row in w:               # each row = one output neuron's weights
        total = Value(0.0)
        for weight, inp in zip(row, x):   # zip pairs each weight with its input
            total = total + weight * inp  # accumulate dot product
        result.append(total)
    return result

Logits 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.

naive softmax logits: [1000, 1001, 999] e^1000 e^1001 e^999 math.exp → OverflowError stable softmax subtract max=1001 first e^-1 e^0 e^-2 p = 0.245, 0.665, 0.090
Naive: math.exp(1000) raises OverflowError, so the naive bars never get a value. Stable: subtract the max (1001) first. The exponents become e^-1, e^0, e^-2, and the probabilities are 0.245, 0.665 and 0.090.
python
def softmax(logits):
    max_logit = max(l.data for l in logits)    # stability: subtract max before exp
    exp_logits = []
    for logit in logits:
        exp_logits.append((logit - max_logit).exp())
    sum_exp = Value(0.0)
    for e in exp_logits:
        sum_exp = sum_exp + e
    result = []
    for e in exp_logits:
        result.append(e / sum_exp)
    return result
 
def rmsnorm(x):
    # divide every element by the root-mean-square of x
    eps = 1e-8
    sq_total = Value(0.0)
    for xi in x:
        sq_total = sq_total + xi ** 2
    mean_sq = sq_total / len(x)
    rms = (mean_sq + eps) ** 0.5
    result = []
    for xi in x:
        result.append(xi / rms)
    return result

After 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.

rmsnorm divides a vector of length nn by its root-mean-square:

rms(x)=1n∑i=1nxi2+ϵ\mathrm{rms}(x) = \sqrt{\frac{1}{n} \sum_{i=1}^{n} x_i^2 + \epsilon} outi=xirms(x)\mathrm{out}_i = \frac{x_i}{\mathrm{rms}(x)}

Normalization keeps activations in a reasonable range. Nothing fancy here. The rewrite uses ϵ=10−8\epsilon = 10^{-8}; Karpathy's file uses 10−510^{-5} (line 105).

Design choice: RMSNorm instead of 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. LLaMA uses RMSNorm too.
RMSNorm: scale activations to unit RMS input x 4.0 -1.5 6.0 -2.5 3.0 -5.0 uneven range ÷ RMS ≈ 3.97 output x / RMS 1.01 -.38 1.51 -.63 0.76 -1.26 compressed to ~unit RMS
Input vector has a wide range (−5 to 6). After dividing by RMS≈3.97, values are compressed to a tighter range (~−1.3 to 1.5). Shape preserved, magnitudes tamed. Animated: input → ÷ RMS → output.

5. attention (lines 115-134)

the problem attention solves

An MLP (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 for the high-level picture.

Q, K, V

Before 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.

Each token projects its embedding through three learned matrices to produce three vectors:

  • Q (query): "what am I looking for?"
  • K (key): "what do I advertise?"
  • V (value): "what do I carry?"

The formula from Attention Is All You Need, with dkd_k the length of one key vector (head_dim = 4 here):

Attn(Q,K,V)=softmax(QKTdk)V\mathrm{Attn}(Q, K, V) = \mathrm{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V

The code below implements that formula, one scalar at a time.

token emb [16] Wq Wk Wv Q [16] looking for? K [16] I advertise? V [16] I carry? score(t,s) = Q[t]·K[s] / √d output = Σ attn[s]*V[s]
Each token projects to Q, K, V via separate learned matrices. Attention score = dot(Q[t], K[s]) / sqrt(head_dim). Output = weighted sum of Vs.

causal masking

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.

The 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.

Without the causal mask every position can see all future tokens (the model learns to copy from the future rather than predict it; cheating)

Result?

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.
  • Training loss, mean of the last 100 steps: 2.28 with the mask, 0.035 without.
  • Held-out loss: 2.352 with the mask, 0.061 without.
  • Samples at T=0.5: names like "anaya" and "rahan" with the mask; 10 of 10 empty without it.
Without the mask, position t reads token t+1 and copies it, on held-out names too. At inference no future tokens exist, so the model has nothing to copy, and it emits BOS at once.

Causal 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).

This 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 avoids storing that matrix. It computes the scores in tiles, so memory grows with T, not T².

attention weights (causal) ▶ (0) e (1) m (2) m (3) ▶(0) e(1) m(2) m(3) query t → key s ↓ 1.0 0.3 0.7 0.1 0.4 0.5 0.1 0.2 0.4 0.3 ✕ ✕ ✕ ✕ ✕ ✕ ✕ = future (masked). Columns fill in as query position grows.
Each column t is one query token. It can only attend to rows s ≤ t, and each column sums to 1. The weights are made-up example values. Animated: columns appear one by one.

multi-head

Split 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.

The output of each attention head is a weighted average of value vectors:

head_out[d]=∑s≤tweights[s]⋅V[s][d]\text{head\_out}[d] = \sum_{s \le t} \text{weights}[s] \cdot V[s][d]

Attention is just a learnable weighted sum.

16-dim q, k, v head 0 [4] head 1 [4] head 2 [4] head 3 [4] attn h0 attn h1 attn h2 attn h3 concat [16] Wo [16×16] out [16]
The 16-dim q, k and v vectors split into 4 heads of 4 dims each. Each head attends on its own. The code concatenates the 4 outputs and projects them through Wo back to 16 dims.

the residual connection

After attention: x = x + attn_out. This is a skip connection, the idea from ResNet. 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.

The residual add happens in gpt() (section 7), not inside attention_block.

python
def attention_block(x_seq, wq_i, wk_i, wv_i, wo_i):
    Q = []
    for x in x_seq:
        Q.append(linear(x, wq_i))
    K = []
    for x in x_seq:
        K.append(linear(x, wk_i))
    V = []
    for x in x_seq:
        V.append(linear(x, wv_i))
 
    out_seq = []
    for t in range(len(x_seq)):
        x_attn = []
        for h in range(n_head):
            start = h * head_dim
            end = (h + 1) * head_dim
            qh = Q[t][start:end]
 
            scores = []
            for s in range(t + 1):  # causal: no peeking at future
                score = Value(0.0)
                for qi, ki in zip(qh, K[s][start:end]):
                    score = score + qi * ki
                score = score / math.sqrt(head_dim)  # scale to stabilize softmax
                scores.append(score)
 
            weights = softmax(scores)
 
            head_out = []
            for d in range(head_dim):
                # weighted sum of values across attended positions
                val = Value(0.0)
                for s in range(t + 1):
                    val = val + weights[s] * V[s][start + d]
                head_out.append(val)
            for elem in head_out:
                x_attn.append(elem)
 
        out_seq.append(linear(x_attn, wo_i))  # mix across heads
    return out_seq
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.

6. the MLP (lines 135-141)

Attention mixes information across positions. MLP processes each position's vector independently. Expand 16 -> 64 (4x width), apply ReLU, project back 64 -> 16.

The logic is simple; more dimensions = more you know about the data (more capacity; intuitive when you think about any data and increase dimensions)

MLP = 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.

In larger models, research finds factual associations stored in the MLP layers (Geva et al. 2021, Meng et al. 2022), things like 'anna' implies female name. Attention routes information; MLP transforms it.

Design choice: ReLU instead of GELU. GELU is smoother and used in GPT-2/GPT-3. ReLU is simpler and works fine here.
16 in 64 hidden (ReLU) 16 out red = killed by ReLU n_embed=16 n_embed=16 same shape as input
16 inputs (blue) fan out to 64 hidden units; the figure draws 34 of them. Green units survive ReLU; ReLU sets the red ones to zero. The survivors fan back in to 16 outputs (orange).
python
def mlp_block(x, w_fc1_i, w_fc2_i):
    x = linear(x, w_fc1_i)          # 16 -> 64: project to wider space
    relu_out = []
    for xi in x:
        relu_out.append(xi.relu())   # non-linearity (ReLU, not GELU)
    x = linear(relu_out, w_fc2_i)   # 64 -> 16: project back
    return x

7. the full forward pass (lines 108-144)

Positional 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 instead of a learned table.

Karpathy's gpt() also applies rmsnorm once to the embedding sum, before the first block (line 112). The rewrite below skips that step.

python
def gpt(tokens):
    # 1. Build input embeddings: add token embedding + position embedding
    # enumerate(tokens) gives (0, tok0), (1, tok1), ...
    # wte[tok] and wpe[pos] are each 16-dim lists; we add them element by element
    x_seq = []
    for pos, tok in enumerate(tokens):
        emb = []
        for te, pe in zip(wte[tok], wpe[pos]):
            emb.append(te + pe)
        x_seq.append(emb)
    # x_seq is now a list of T vectors, each of length 16
 
    for i in range(n_layer):
        # 2. Normalize, run attention, add residual (x = x + attn_out)
        normed = []
        for x in x_seq:
            normed.append(rmsnorm(x))
        attn_out = attention_block(normed, wq[i], wk[i], wv[i], wo[i])
        new_x_seq = []
        for attn, x in zip(attn_out, x_seq):
            combined = []
            for a, b in zip(attn, x):          # add skip connection
                combined.append(a + b)          # new_x[d] = attn_out[d] + old_x[d]
            new_x_seq.append(combined)
        x_seq = new_x_seq
 
        # 3. Normalize, run MLP, add residual (same pattern)
        new_x_seq = []
        for x in x_seq:
            mlp_out = mlp_block(rmsnorm(x), w_fc1[i], w_fc2[i])
            combined = []
            for a, b in zip(mlp_out, x):
                combined.append(a + b)
            new_x_seq.append(combined)
        x_seq = new_x_seq
 
    # 4. Project each position's 16-dim vector to 27 logits (one per vocab token)
    logits_seq = []
    for x in x_seq:
        logits_seq.append(linear(x, lm_head))
    return logits_seq

Shape walkthrough for input "em" (BOS plus 2 letters, e=4, m=12):

text
tokens = [26, 4, 12]             # BOS, 'e', 'm'        shape: [3]
x_seq  = [[...], [...], [...]]   # after wte+wpe         shape: [3, 16]
normed = [[...], [...], [...]]   # after rmsnorm          shape: [3, 16]
attn_out = [[...], [...], [...]] # after attention        shape: [3, 16]
x_seq (residual) = x_seq + attn_out                      shape: [3, 16]
mlp_out = [[...], [...], [...]]  # after mlp              shape: [3, 16]
x_seq (residual) = x_seq + mlp_out                       shape: [3, 16]
logits = [[...], [...], [...]]   # after lm_head          shape: [3, 27]

Each token and its position each contribute a learned 16-dim vector. The code adds the two vectors element by element.

The result is the model's complete representation of "this token at this position."

tokens [T] wte + wpe x_seq [T × 16] × n_layer RMSNorm Attention + residual RMSNorm MLP + residual lm_head logits [T × 27]
Full forward pass. Pre-norm (RMSNorm before attention/MLP) is more stable than post-norm. Residual connections after each sub-layer.

Pre-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.

The 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.


8. training loop (lines 146-184)

loss: cross-entropy

Cross-entropy loss = -log(p[target]).

If the model assigns 90% probability to the correct token: loss = -log(0.9) = 0.11.

If it assigns 1%: loss = -log(0.01) = 4.6.

The 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.

Why 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.

cross-entropy: -log(p) p(correct token) loss 0 0.5 1.0 1/27 ≈3.3 p=0.9 ≈0.1 target
Random model gives uniform probability ≈ 1/27, loss = ln 27 ≈ 3.3. A good model gives high p to the correct token, loss near 0. The dot shows what training does: it pushes the model rightward and down this curve.

backward + SGD

python
learning_rate = 0.01
num_steps = 20
batch_size = 8
 
for step in range(num_steps):
    total_loss = Value(0.0)
 
    for b in range(batch_size):
        # modulo wraps around so we cycle through all docs repeatedly
        doc = docs[(step * batch_size + b) % len(docs)]
        # chars.index(c) converts each character to its integer ID
        char_tokens = []
        for c in doc:
            char_tokens.append(chars.index(c))
        tokens = [BOS] + char_tokens + [BOS]
        tokens = tokens[:block_size + 1]    # at most 16 inputs; longest name is 15 chars
 
        input_tokens  = tokens[:-1]         # model sees this
        target_tokens = tokens[1:]          # model must predict this
 
        logits_seq = gpt(input_tokens)
 
        loss = Value(0.0)
        for logits, target in zip(logits_seq, target_tokens):
            probs = softmax(logits)
            loss = loss + (-probs[target].log())   # negative log-likelihood
        total_loss = total_loss + loss / len(logits_seq)
 
    avg_loss = total_loss / batch_size
    avg_loss.backward()          # backprop through the ENTIRE Value graph
 
    # SGD: param -= lr * grad
    for param in params:
        param.data -= learning_rate * param.grad
        param.grad = 0           # must reset or gradients accumulate
 
    print(f"Step {step+1}/{num_steps}, Loss: {avg_loss.data:.4f}")

Gradients 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.

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 Adam from scratch and the Adam paper.

Loss 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".

Karpathy's script trains with Adam on one name per step, for 1,000 steps:

text
$ python microgpt.py
num docs: 32033
vocab size: 27
num params: 4192
step    1 / 1000 | loss 3.3660
step    6 / 1000 | loss 2.9452
step   11 / 1000 | loss 2.7964
step   13 / 1000 | loss 3.0544
...
step 1000 / 1000 | loss 2.6497

Each 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.

What 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."

training loss, Karpathy's script, 1,000 steps step loss 1 500 1000 2 3 3.30 2.32
Grey: the loss of each step (every 5th step drawn). Blue: the mean over 50 steps, from 2.85 down to 2.32. The red line is ln 27 ≈ 3.30, the loss of a uniform guess. One name per step makes the raw loss noisy.
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.

9. inference (lines 186-200)

Start 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).

That'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.

Temperature is logit / T before softmax. If the model's top logit is 2.0 and second is 1.5:

  • T=0.5: logits become 4.0 and 3.0. The gap widens, and the top token dominates.
  • T=1.0: unchanged
  • T=2.0: logits become 1.0 and 0.75. The gap narrows, and the distribution gets more even.

Temperature controls the entropy of the output distribution (temperature in the ChatGPT post).

  • T → 0 approaches argmax (always pick the most likely token, no diversity). The code divides by T, so T=0 itself raises ZeroDivisionError.
  • T=1 samples from the raw model distribution
  • T>1 flattens the distribution (more surprising outputs)

Sampling 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.

Attention 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.

a e m n r s p=0.83 T = 0.5 (sharp) p=0.54 T = 1.0 (natural) p=0.33 T = 2.0 (flat)
Same logits (a 1.0, e 2.0, m 0.3, n −0.5, r 0.0, s −0.3), bar height = softmax(logits / T). T=0.5 puts 0.83 of the probability on 'e'. T=2.0 flattens it to 0.33. Animated: cycles through T=0.5, 1.0, 2.0.
python
temperature = 0.5
for _ in range(10):
    context = [BOS]
    name = ""
    for _ in range(block_size):
        logits_seq = gpt(context)
        # apply temperature: divide logits before softmax
        # lower temperature = model picks safer, more common tokens
        logits_t = []
        for l in logits_seq[-1]:
            logits_t.append(l / temperature)
        probs = softmax(logits_t)
        prob_data = []
        for p in probs:
            prob_data.append(p.data)
        next_token = random.choices(range(vocab_size), weights=prob_data)[0]
        if next_token == BOS:    # BOS doubles as end-of-name sentinel
            break
        context.append(next_token)
        name += chars[next_token]
    print(name)

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].

Karpathy's script prints these 20 samples after its 1,000 Adam steps (seed 42, T=0.5):

text
sample  1: kamon
sample  2: ann
sample  3: karai
sample  4: jaire
sample  5: vialan
sample  6: karia
sample  7: yeran
sample  8: anna
sample  9: areli
sample 10: kaina
sample 11: konna
sample 12: keylen
sample 13: liole
sample 14: alerin
sample 15: earan
sample 16: lenne
sample 17: kana
sample 18: lara
sample 19: alela
sample 20: anton

The 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.

Temperature 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:

  • T=0.5: 11 of 20 ("anna", "lara", "anton")
  • T=1.0: 3 of 20
  • T=1.5: 0 of 20, and some are unpronounceable, like "hisvnof" and "nchhry"

10. from microgpt to chatgpt

OpenAI 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.

microGPTGPT-3 / ChatGPT
32K names300B training tokens (GPT-3)
4,192 params, 1 layer175B params, 96 layers
Adam + linear LR decay (Karpathy), SGD (the rewrite)Adam + LR warmup and cosine decay + grad clipping
no post-trainingSFT + RLHF (ChatGPT)

Same algorithm. Scale and engineering differ. The tokenizer, the serving stack and the rest of the gap are in how ChatGPT works.

The 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.


references

reply by email

related