Lesson 4.3: Assembling a GPT from blocks, norms and an output layer
Put attention, feed-forward layers, residual connections and norms into a full GPT, write its backward pass, train it and measure what each part adds.
By the end of this lesson you will be able to write a complete GPT-style model in NumPy, forward and backward, check its gradients, train it on the toy language and say what each part contributes. You will show that its gradients match numerical ones in four configurations (worst relative errors 5.3e-07, 5.1e-08, 3.5e-06 and 1.2e-06), that a two-block model of 27,648 numbers reaches a validation loss of 1.0024 (seed spread 0.0006) against 1.0061 for the one-head layer of Lesson 3.2, that removing the feed-forward layer, the layer norms or switching to post-norm costs only 0.004 to 0.005 on this easy language, that at 8 layers and a high learning rate pre-norm trains (1.0484) while post-norm does not (3.1879) and no norm diverges, and that 98.9% of 533 generated sentences follow the grammar of the toy language. You need Python and NumPy, and helpers.py from Lesson 3.1.
Modules 2 and 3 gave us every ingredient: tokens and positions, attention with a mask and heads, and a cache for generation. Lessons 4.1 and 4.2 added residual connections, layer norm and the feed-forward layer. This lesson puts them together. The result is a GPT: a stack of identical blocks, each of which reads and writes a residual stream, between an embedding at the bottom and an output matrix at the top. It is the architecture, at small scale, of the models that write text today.
The block, and the model
One block has two sublayers, each wrapped in a norm at its input and a residual add at its output (the pre-norm arrangement of Lesson 4.1):
x = x + Attention(LayerNorm(x))
x = x + FeedForward(LayerNorm(x))
The model is:
tokens -> embedding table + positions (B, T, d)
-> block 1 -> block 2 -> ... -> block L (B, T, d), the residual stream
-> final LayerNorm
-> output matrix U (B, T, V): scores for the next token
-> softmax and cross-entropy against the shifted targets
Nothing else. Every block has the same shape and its own weights. A bigger model has a bigger d, more blocks and more heads, and the same code.
The code
Here is the whole model with its backward pass. Save it as gpt.py. It reads from top to bottom in three parts. First the pieces: a linear layer, layer norm, GELU, attention and the feed-forward layer, each as a pair of functions, the forward returning its result and a cache and the backward taking the gradient of the output and returning the gradients of the input and the weights. Then the model: initgpt builds the weights, gptfwd runs the blocks, gptbwd runs them in reverse. Finally lossandgrads ties them to the loss.
python
# gpt.py
import numpy as np
from helpers import softmax
---------- pieces: each forward returns (output, cache); each backward returns gradients ----------
def linearfwd(x, W, b):
return x @ W + b, (x, W)
def linearbwd(dy, cache):
x, W = cache
dx = dy @ W.T
dW = x.reshape(-1, x.shape[-1]).T @ dy.reshape(-1, dy.shape[-1])
db = dy.sum(axis=tuple(range(dy.ndim - 1)))
return dx, dW, db
def lnfwd(x, g, b, eps=1e-5):
mu = x.mean(axis=-1, keepdims=True)
var = x.var(axis=-1, keepdims=True)
xhat = (x - mu) / np.sqrt(var + eps)
return g xhat + b, (xhat, g, var, eps)
def lnbwd(dy, cache):
xhat, g, var, eps = cache
dxhat = dy g
dx = (dxhat - dxhat.mean(-1, keepdims=True) - xhat (dxhat xhat).mean(-1, keepdims=True)) / np.sqrt(var + eps)
dg = (dy xhat).reshape(-1, xhat.shape[-1]).sum(0)
db = dy.reshape(-1, xhat.shape[-1]).sum(0)
return dx, dg, db
def gelufwd(x):
c = np.sqrt(2 / np.pi)
t = np.tanh(c (x + 0.044715 x 3))
return 0.5 x (1 + t), (x, t)
def gelubwd(dy, cache):
x, t = cache
c = np.sqrt(2 / np.pi)
dt = (1 - t 2) c (1 + 3 0.044715 x 2)
return dy (0.5 (1 + t) + 0.5 x dt)
def attnfwd(p, x, h, causal=True):
B, T, d = x.shape
dh = d // h
q, cq = linearfwd(x, p["Wq"], p["bq"]); k, ck = linearfwd(x, p["Wk"], p["bk"]); v, cv = linearfwd(x, p["Wv"], p["bv"])
split = lambda z: z.reshape(B, T, h, dh).transpose(0, 2, 1, 3)
Q, K, Vv = split(q), split(k), split(v)
S = np.einsum("bhtd,bhsd->bhts", Q, K) / np.sqrt(dh)
if causal:
S = np.where(np.triu(np.ones((T, T), dtype=bool), 1), -1e9, S)
A = softmax(S)
O = np.einsum("bhts,bhsd->bhtd", A, Vv).transpose(0, 2, 1, 3).reshape(B, T, d)
y, co = linearfwd(O, p["Wo"], p["bo"])
return y, (cq, ck, cv, co, Q, K, Vv, A, h, dh)
def attnbwd(dy, cache):
cq, ck, cv, co, Q, K, Vv, A, h, dh = cache
B, T, d = dy.shape
dO, dWo, dbo = linearbwd(dy, co)
dO = dO.reshape(B, T, h, dh).transpose(0, 2, 1, 3)
dA = np.einsum("bhtd,bhsd->bhts", dO, Vv)
dV = np.einsum("bhts,bhtd->bhsd", A, dO)
dS = A (dA - (dA A).sum(-1, keepdims=True)) / np.sqrt(dh)
dQ = np.einsum("bhts,bhsd->bhtd", dS, K)
dK = np.einsum("bhts,bhtd->bhsd", dS, Q)
merge = lambda z: z.transpose(0, 2, 1, 3).reshape(B, T, d)
dxq, dWq, dbq = linearbwd(merge(dQ), cq)
dxk, dWk, dbk = linearbwd(merge(dK), ck)
dxv, dWv, dbv = linearbwd(merge(dV), cv)
return dxq + dxk + dxv, dict(Wq=dWq, bq=dbq, Wk=dWk, bk=dbk, Wv=dWv, bv=dbv, Wo=dWo, bo=dbo)
def mlpfwd(p, x):
a, c1 = linearfwd(x, p["W1"], p["c1"])
z, cg = gelufwd(a)
y, c2 = linearfwd(z, p["W2"], p["c2"])
return y, (c1, cg, c2)
def mlpbwd(dy, cache):
c1, cg, c2 = cache
dz, dW2, dc2 = linearbwd(dy, c2)
da = gelubwd(dz, cg)
dx, dW1, dc1 = linearbwd(da, c1)
return dx, dict(W1=dW1, c1=dc1, W2=dW2, c2=dc2)
---------- the model ----------
def initgpt(V, d, L, seed=0, std=0.02, residscale=True):
rng = np.random.defaultrng(seed)
n = lambda s, sd=std: rng.standardnormal(s) sd
p = {"E": n(V, d), "U": n(d, V), "gf": np.ones(d), "bf": np.zeros(d)}
rs = std / np.sqrt(2 L) if residscale else std # shrink the layers that write into the residual stream
for l in range(L):
k = f"{l}."
p.update({k + "g1": np.ones(d), k + "b1": np.zeros(d), k + "g2": np.ones(d), k + "b2": np.zeros(d),
k + "Wq": n(d, d), k + "bq": np.zeros(d), k + "Wk": n(d, d), k + "bk": np.zeros(d),
k + "Wv": n(d, d), k + "bv": np.zeros(d), k + "Wo": n(d, d, sd=rs), k + "bo": np.zeros(d),
k + "W1": n(d, 4 d), k + "c1": np.zeros(4 d), k + "W2": n(4 d, d, sd=rs), k + "c2": np.zeros(d)})
return p
def sub(p, l):
k = f"{l}."
return {n[len(k):]: v for n, v in p.items() if n.startswith(k)}
def gptfwd(p, x, L, h, Pos, prenorm=True, usemlp=True, useln=True):
B, T = x.shape
H = p["E"][x] + Pos[:T]
caches = []
for l in range(L):
q = sub(p, l); c = {}
if prenorm:
ain, c["ln1"] = lnfwd(H, q["g1"], q["b1"]) if useln else (H, None)
a, c["attn"] = attnfwd(q, ain, h)
H = H + a
if usemlp:
min, c["ln2"] = lnfwd(H, q["g2"], q["b2"]) if useln else (H, None)
m, c["mlp"] = mlpfwd(q, min)
H = H + m
else: # post-norm: normalise after adding
a, c["attn"] = attnfwd(q, H, h)
H, c["ln1"] = lnfwd(H + a, q["g1"], q["b1"]) if useln else (H + a, None)
if usemlp:
m, c["mlp"] = mlpfwd(q, H)
H, c["ln2"] = lnfwd(H + m, q["g2"], q["b2"]) if useln else (H + m, None)
caches.append(c)
Hf, cf = lnfwd(H, p["gf"], p["bf"]) if (useln and prenorm) else (H, None)
logits = Hf @ p["U"]
return logits, dict(x=x, caches=caches, cf=cf, Hf=Hf, H=H, L=L, prenorm=prenorm, usemlp=usemlp, useln=useln)
def gptbwd(p, c, dlogits):
g = {}
L = c["L"]
g["U"] = np.einsum("btd,btv->dv", c["Hf"], dlogits)
dH = dlogits @ p["U"].T
if c["useln"] and c["prenorm"]:
dH, g["gf"], g["bf"] = lnbwd(dH, c["cf"])
else:
g["gf"], g["bf"] = np.zeroslike(p["gf"]), np.zeroslike(p["bf"])
for l in reversed(range(L)):
q = sub(p, l); cc = c["caches"][l]; k = f"{l}."
gl = {}
if c["prenorm"]:
if c["usemlp"]:
dm, gm = mlpbwd(dH, cc["mlp"]); gl.update(gm)
if c["useln"]:
dm, gl["g2"], gl["b2"] = lnbwd(dm, cc["ln2"])
dH = dH + dm
da, ga = attnbwd(dH, cc["attn"]); gl.update(ga)
if c["useln"]:
da, gl["g1"], gl["b1"] = lnbwd(da, cc["ln1"])
dH = dH + da
else:
if c["usemlp"]:
dS = dH
if c["useln"]:
dS, gl["g2"], gl["b2"] = lnbwd(dH, cc["ln2"])
dm, gm = mlpbwd(dS, cc["mlp"]); gl.update(gm)
dH = dS + dm
dS = dH
if c["useln"]:
dS, gl["g1"], gl["b1"] = lnbwd(dH, cc["ln1"])
da, ga = attnbwd(dS, cc["attn"]); gl.update(ga)
dH = dS + da
for name in q:
g[k + name] = gl.get(name, np.zeroslike(q[name]))
g["E"] = np.zeroslike(p["E"])
np.add.at(g["E"], c["x"], dH)
return g
def lossandgrads(p, x, y, L, h, Pos, kw):
logits, c = gptfwd(p, x, L, h, Pos, kw)
P = softmax(logits)
B, T = y.shape
loss = -np.log(P[np.arange(B)[:, None], np.arange(T)[None, :], y]).mean()
dl = P.copy(); dl[np.arange(B)[:, None], np.arange(T)[None, :], y] -= 1; dl /= B T
return loss, gptbwd(p, c, dl)
Seven points make it easy to read.
Names of weights. Block l keeps its weights in entries named "l.Wq", "l.W1" and so on. sub(p, l) pulls out one block's weights. The embedding table is E, the output matrix U, the final norm gf and bf.
The residual adds. H = H + a and H = H + m are the residual connections. In the backward pass, a gradient arriving at H goes to both the sublayer and straight past it: dH = dH + da.
Pre-norm and post-norm. The flag prenorm selects the arrangement. In the post-norm branch the norm is applied after the add, and there is no final norm.
Ablation flags. usemlp=False skips the feed-forward layer and useln=False skips the norms. We use them to measure what each part contributes. The weights still exist, so the parameter count stays the same.
Initialisation. initgpt draws weights from a normal distribution with a small spread (0.02). The two matrices that write into the stream, Wo and W2, are made smaller by 1 over the square root of 2 L. Lesson 4.4 explains why.
Positions. We keep the fixed sinusoidal positions of Lesson 2.3 (Pos). Most GPTs learn a position table instead. It is an extra table of T by d numbers.
No cache here. The forward pass processes whole windows. Lesson 3.4's cache is used at generation time, and is not needed for training.
Check the gradients
A hand-written backward pass through a stack of different layers has many places for a mistake. We check twelve random parameters, in each of four configurations, against numerical gradients.
python
import numpy as np
from helpers import
from gpt import
d, L, h, T = 16, 2, 2, 6
Pos = sinusoidal(T, d)
x, y = getbatch(trainids, 3, T, np.random.defaultrng(5))
rng = np.random.defaultrng(0)
for kw in ({}, dict(prenorm=False), dict(useln=False), dict(usemlp=False)):
p = initgpt(V, d, L, seed=1, std=0.3, residscale=False)
for name in p: # make every parameter non-trivial
if name.endswith(("g1", "g2", "gf")): p[name] = 1 + 0.3 rng.standardnormal(p[name].shape)
if name.endswith(("b1", "b2", "bf", "bq", "bk", "bv", "bo", "c1", "c2")): p[name] = 0.3 rng.standardnormal(p[name].shape)
loss, g = lossandgrads(p, x, y, L, h, Pos, kw)
worst = 0.0
for name in rng.choice(list(p), 12, replace=False): # twelve random parameters
w = p[name]
idx = tuple(rng.integers(0, s) for s in w.shape)
eps, old = 1e-6, w[idx]
w[idx] = old + eps; lp, = lossandgrads(p, x, y, L, h, Pos, kw)
w[idx] = old - eps; lm, = lossandgrads(p, x, y, L, h, Pos, kw)
w[idx] = old
num = (lp - lm) / (2 eps)
worst = max(worst, abs(g[name][idx] - num) / max(abs(num), abs(g[name][idx]), 1e-4))
print(f"{str(kw):22s} worst relative error {worst:.1e}")
The output:
{} worst relative error 5.3e-07
{'prenorm': False} worst relative error 5.1e-08
{'useln': False} worst relative error 3.5e-06
{'usemlp': False} worst relative error 1.2e-06
All four are far below 1e-5, so the backward pass is right for the full block, post-norm, no norms and no feed-forward layer. (The error is relative to the larger of the two gradients, with a floor of 1e-4, so that gradients that are nearly zero do not produce a spurious large ratio.)
Training it
Save this helper as train.py. It trains for a given configuration and reports the loss at step 0 and the validation loss. The defaults are a width of 32, two blocks, two heads, windows of 16, batches of 32 windows, Adam with a step of 0.003 and 3,000 steps.
python
# train.py
import numpy as np
from helpers import
from gpt import
T = 16
def train(d=32, L=2, h=2, lr=0.003, steps=3000, seed=0, std=0.02, residscale=True, kw):
Pos = sinusoidal(T, d)
p = initgpt(V, d, L, seed=seed, std=std, residscale=residscale)
opt = Adam(p, lr)
rng = np.random.defaultrng(seed)
first = None
for step in range(steps):
x, y = getbatch(trainids, 32, T, rng)
loss, g = lossandgrads(p, x, y, L, h, Pos, kw)
if step == 0:
first = loss
opt.step(g)
return p, first
def validation(p, d=32, L=2, h=2, kw):
x, y = getbatch(valids, 400, T, np.random.defaultrng(123))
logits, = gptfwd(p, x, L, h, sinusoidal(T, d), kw)
P = softmax(logits)
return -np.log(P[np.arange(400)[:, None], np.arange(T)[None, :], y]).mean()
A good first check: the loss at step 0 should be close to the natural log of the vocabulary size, since an untrained model should be uniformly unsure. For 34 words, that is 3.5264. Our model reports 3.530. That is the sign of a sound initialisation, and Lesson 4.4 returns to it.
Now train the full block and three variants:
python
from train import
variants = {"full block": {}, "no feed-forward layer": dict(usemlp=False),
"no layer norm": dict(useln=False), "post-norm": dict(prenorm=False)}
for name, kw in variants.items():
p, first = train(kw)
print(f"{name:24s} loss at step 0: {first:.3f} validation: {validation(p, kw):.4f} parameters: {sum(w.size for w in p.values())}")
full block loss at step 0: 3.530 validation: 1.0024 parameters: 27648
no feed-forward layer loss at step 0: 3.530 validation: 1.0065 parameters: 27648
no layer norm loss at step 0: 3.524 validation: 1.0054 parameters: 27648
post-norm loss at step 0: 3.530 validation: 1.0052 parameters: 27648
The full block reaches 1.0024, better than the one-head layer of Lesson 3.2 (1.0061) and the fixed weights of Lesson 3.1 (1.0095), and close to the trigram table (0.992) and the best possible (0.988). To know how much of a difference is noise, we train the full block with three seeds:
python
from train import
scores = []
for seed in (0, 1, 2):
p, = train(seed=seed)
scores.append(validation(p))
print("seed", seed, "validation", round(float(scores[-1]), 4))
print("spread between seeds:", round(float(np.std(scores)), 4))
seed 0 validation 1.0024
seed 1 validation 1.0014
seed 2 validation 1.0009
spread between seeds: 0.0006
The seed-to-seed spread is 0.0006. The three ablations are worse by 0.004 to 0.005 (1.0065, 1.0054 and 1.0052 against about 1.0016 for the average of the three seeds), which is several times the noise, so they are real. But they are small. Removing the feed-forward layer, which holds two thirds of the block's parameters, costs 0.005.
That is the honest result, and it has a reason: the toy language is easy. Its next word depends on the previous two. One attention layer with fixed weights nearly captures that, and everything beyond leaves very little to gain, since the floor is 0.988. We are at 1.0024, within 0.014 of the floor. The parts of the block earn their place on harder problems and deeper models, where the differences are large. We can see this directly by making the problem harder in another way: depth and a high learning rate.
Depth, learning rate and the norms
Lesson 4.1 argued that residual connections and layer norms matter more as models get deeper. Here is the test: eight blocks of width 16, trained for 800 steps, at a gentle learning rate (0.003) and a high one (0.03), with pre-norm, post-norm and no norm.
python
from train import
for lr in (0.003, 0.03):
for name, kw in {"pre-norm": {}, "post-norm": dict(prenorm=False), "no layer norm": dict(useln=False)}.items():
with np.errstate(all="ignore"):
p, first = train(d=16, L=8, lr=lr, steps=800, kw)
print(f"lr {lr:<6} {name:14s} validation: {validation(p, d=16, L=8, kw):.4f}")
lr 0.003 pre-norm validation: 1.0051
lr 0.003 post-norm validation: 1.0036
lr 0.003 no layer norm validation: 1.0077
lr 0.03 pre-norm validation: 1.0484
lr 0.03 post-norm validation: 3.1879
lr 0.03 no layer norm validation: inf
At the gentle rate, all three work and are within 0.004 of each other. At the high rate, the story changes sharply. Pre-norm trains: 1.0484, a little behind, as a high rate is noisy. Post-norm fails: 3.1879 is nearly as bad as guessing (3.5264). No norm diverges: the loss became infinite, because activations overflowed. This is the practical case for pre-norm and for norms at all: they widen the range of learning rates that work. Every serious model is trained near the top of that range, since a larger rate means faster learning.
Does it write the language?
Finally, we generate text from the trained two-block model by sampling one token at a time, and test whether it follows the toy grammar.
python
import re
from train import
p, = train()
Pos = sinusoidal(T, 32)
def generate(p, n, seed):
rng = np.random.defaultrng(seed)
toks = [stoi["."]]
for in range(n):
ctx = np.array([toks[-T:]])
logits, = gptfwd(p, ctx, 2, 2, Pos)
toks.append(int(rng.choice(V, p=softmax(logits[0, -1]))))
return " ".join(vocab[t] for t in toks[1:])
text = generate(p, 4000, seed=1)
print(text[:150])
grammar = re.compile(r"^(the cat|the dog|a bird|the child|my teacher|the farmer|a fox|the baker) "
r"(chased|watched|found|followed|liked|saw) "
r"(the ball|a fish|the red bus|a small boat|the old tree|a loud drum)"
r"( quickly| slowly| today| again| at night)?
quot;)
sentences = [s.strip() for s in text.split(".")[1:-1]] # drop the possibly cut first and last pieces
ok = sum(bool(grammar.match(s)) for s in sentences)
print(len(sentences), "sentences,", ok, "follow the grammar:", round(100 ok / len(sentences), 1), "%")
the farmer followed the old tree slowly . the baker saw a fish slowly . the baker found a fish quickly . the farmer watched the old tree . the child c
533 sentences, 527 follow the grammar: 98.9 %
The text reads like the corpus. The check splits 4,000 sampled tokens at the full stops, drops the possibly cut first and last pieces, and tests each of the 533 sentences against the grammar (one of eight subjects, one of six verbs, one of six objects, an optional adverb). 527 of 533 pass, 98.9%. The model has learned the grammar from examples, with 27,648 numbers. The six that fail are sampling slips: with a temperature of one, the model sometimes picks an unlikely word, and an unlikely word can break the pattern. Lesson 6.1 returns to sampling.
What the whole model costs per token
The forward pass of one token costs, in multiply-adds, about 12 d² + 2 T d per block (4 d² for the attention projections, 8 d² for the feed-forward layer, and 2 T d for the scores and mixing) and V d for the output matrix. For our model, d = 32, L = 2, T = 16 and V = 34: 13,312 per block, 26,624 for both, plus 1,088 for the output layer, 27,712 in all. The output layer is only 3.9% of the work here, and for a large vocabulary it is much more.
Key takeaways
A GPT is an embedding plus positions, a stack of L identical pre-norm blocks, a final layer norm, and an output matrix. Each block does x = x + Attention(Norm(x)) and then x = x + FeedForward(Norm(x)).
Write each piece as a forward and backward pair, and run the backward in reverse. A residual add sends the gradient both through the sublayer and straight past it.
Check the gradients in every configuration you intend to use. Ours matched numerical gradients to relative errors between 5.1e-08 and 3.5e-06.
At initialisation, the loss should be close to the log of the vocabulary size: 3.530 against 3.5264.
The two-block GPT (27,648 numbers) reached a validation loss of 1.0024 with a seed spread of 0.0006. That is ahead of one attention head (1.0061) and 0.014 above the floor (0.988).
Removing the feed-forward layer, the norms or using post-norm cost only 0.004 to 0.005. The toy language is easy, so the parts show their value when the task is harder.
At 8 blocks and a learning rate of 0.03, pre-norm trained (1.0484), post-norm did not (3.1879), and no norm diverged. Norms widen the range of learning rates that work.
98.9% of 533 sampled sentences followed the grammar.
Per token, a block costs about 12 d² + 2 T d multiply-adds, and the output matrix V d.
Common mistakes
Not checking the backward pass. Each of the many pieces can hide an error, and the loss may still fall slowly with a wrong gradient.
Forgetting the residual path in the backward pass. The gradient must reach the stream directly as well as through the sublayer.
Comparing variants with one seed. Differences smaller than the seed-to-seed spread mean nothing.
Concluding a part is useless because an easy task does not need it. Test on a harder problem, a deeper model or a higher learning rate.
Training at a gentle rate only. Problems with the norms show up at higher rates.
Starting with a loss far above the log of the vocabulary. The initial weights are too large, or the output is not centred.
Sampling at temperature one and blaming the model for every slip. Sampling noise contributes. Lesson 6.1 covers it.
Skipping the final norm in pre-norm. The stream's scale grows with depth, so the output sees an unnormalised vector.
Check yourself
1. What are the two sublayers of a block, and how is each wrapped?
Attention and the feed-forward layer. Each has a layer norm at its input and a residual add at its output: x = x + Sublayer(LayerNorm(x)).
2. What should the loss be at step 0 for a vocabulary of 50,000, and why?
About ln 50,000 = 10.82, since an untrained model should give every token about the same probability.
3. Three seeds give validation losses of 1.002, 1.001 and 1.003. A variant scores 1.004. Is it worse?
The spread is about 0.001, and the variant is 0.002 above the mean of 1.002. It is slightly worse, around two spreads, but not decisively.
4. At d = 512, T = 1,024, L = 8, V = 32,000, how many multiply-adds does one token cost?
Per block 12 × 512² + 2 × 1,024 × 512 = 3,145,728 + 1,048,576 = 4,194,304. Eight blocks: 33,554,432. Output matrix: 32,000 × 512 = 16,384,000. Total 49,938,432.
5. Why does pre-norm tolerate a higher learning rate than post-norm?
In pre-norm the residual path is a clean sum and the norms act only on the sublayer inputs, so gradients flow without passing through a normalisation at every layer. In post-norm, each layer's output goes through a norm on the main path, which makes training more sensitive to the step size.
6. In the backward pass of a residual add H = H + a, where does the gradient of H go?
To both the sublayer's output, which feeds back through the sublayer, and directly to the input of the add, unchanged.
Try this
Set aside three hours. You need Python, NumPy, helpers.py, gpt.py and train.py.
1. Run the gradient check. Break the backward pass on purpose, by removing the residual dH = dH + da line, and see how large the error becomes.
2. Train the full block with width 64 and four heads. Does the validation loss move? How many numbers does the model have?
3. Train with 1, 2, 4 and 6 blocks at width 32. Where do the returns stop?
4. Add a learned position table in place of the sinusoidal one, as a parameter Pos with its gradient. Does the loss change?
5. Tie the output matrix to the embedding table (U = E.T), and add the gradient of the output matrix into E's gradient. How many numbers do you save, and what happens to the loss?
6. Generate with temperatures of 0.5, 1.0 and 1.5 (divide the scores by the temperature before the softmax). How does the share of grammatical sentences change?
7. Find the learning rate at which pre-norm itself begins to fail at 8 blocks.
A good result is a model whose gradients pass the check, a validation loss near 1.002, a measured effect of depth and learning rate on the norms and a generated text that follows the grammar. The next lesson is about the numbers inside the model: how to initialise them, how to count them and what shape each has.
Read more
Alec Radford and colleagues, "Language Models are Unsupervised Multitask Learners" (2019), describes GPT-2, the architecture this lesson builds at small scale, including its pre-norm blocks and the scaled initialisation of the residual layers. Ashish Vaswani and colleagues, "Attention Is All You Need" (2017), is the original block. Ruibin Xiong and colleagues, "On Layer Normalization in the Transformer Architecture" (2020), compares pre-norm and post-norm. Andrej Karpathy's lecture "Let's build GPT: from scratch, in code, spelled out" builds the same model in PyTorch.
Tags: Build an LLM GPT Transformer block Pre-norm Training