GPT from code · part 1 of 5

The whole model: from a name to the next character

A tiny GPT trained on Catalan first names (nomsCatalunya.txt), read straight from the code. Example name: “marta”.

1“marta” → characters + BOS
BOSmartaBOS
input_ids = tokens[:T], T = 6
BOS
position 0
m
position 1
a
position 2
r
position 3
t
position 4
a
position 5
m
a
r
t
a
BOS
+
wte[BOS] + wpe[0]
+
wte[m] + wpe[1]
+
wte[a] + wpe[2]
+
wte[r] + wpe[3]
+
wte[t] + wpe[4]
+
wte[a] + wpe[5]
Masked multi-head self-attentioneach position looks at itself and the positions before it
MLP 128 → 512 → 128 (ReLU)each position on its own

p(next = “m”)

p(next = “a”)

p(next = “r”)

p(next = “t”)

p(next = “a”)

p(next = “BOS”)
6loss = average over the 6 positions of −log p(correct next character)
cross-entropy: small when the model gives a high probability to the right character
7Training: autograd → gradients
Adam · lr 0.001 → 0 · 10,000 steps, one name per step
2Targets · tokens[1:]
at each position, the character that comes next
3Embeddings → x (6 × 128)
x = wte[ids] + wpe[pos], then RMSNorm. The token says what, the position says where.
43 transformer blocks (n_layer = 3)
Each block = attention + MLP, each wrapped in RMSNorm and a residual connection.
5LM head + softmax
logits = x · lm_headᵀ: one score per character of the vocabulary, turned into probabilities.