The annotated microGPT
contents
- 1. data (lines 1-27)
- 2. autograd engine (lines 29-72)
- 3. hyperparameters and weight init (lines 74-90)
- 4. utility functions (lines 94-106)
- 5. attention (lines 115-134)
- 6. the MLP (lines 135-141)
- 7. the full forward pass (lines 108-144)
- 8. training loop (lines 146-184)
- 9. inference (lines 186-200)
- 10. from microgpt to chatgpt
- 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'sgpt()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).
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":
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:
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.
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 to the input does to the output. Does the output increase or decrease, and by how much?
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.
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 * otherThe 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.
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 rule3. hyperparameters and weight init (lines 74-90)
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 # = 4Each 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.
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 resultThe 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:
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:
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 16The code collects every parameter Value into one flat list, so the SGD loop can update all 4,192 parameters in a single pass:
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)}") # 4192This 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.
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 resultLogits 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.
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 resultAfter 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 by its root-mean-square:
Normalization keeps activations in a reasonable range. Nothing fancy here. The rewrite uses ; Karpathy's file uses (line 105).
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 the length of one key vector (head_dim = 4 here):
The code below implements that formula, one scalar at a time.
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?
- 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.
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².
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:
Attention is just a learnable weighted sum.
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.
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_seq6. 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.
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 x7. 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.
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_seqShape walkthrough for input "em" (BOS plus 2 letters, e=4, m=12):
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."
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.
backward + SGD
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.
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:
$ 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.6497Each 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."
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.
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):
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: antonThe 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.
| microGPT | GPT-3 / ChatGPT |
|---|---|
| 32K names | 300B training tokens (GPT-3) |
| 4,192 params, 1 layer | 175B params, 96 layers |
| Adam + linear LR decay (Karpathy), SGD (the rewrite) | Adam + LR warmup and cosine decay + grad clipping |
| no post-training | SFT + 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
- Karpathy's microgpt.py and his blog post about it
- Karpathy's makemore: the dataset and spirit
- Andrej Karpathy: The spelled-out intro to language modeling
- Jay Alammar: The Illustrated Transformer
- Jay Alammar: The Illustrated GPT-2
- Vaswani et al. (2017): Attention Is All You Need