Transformers
The Transformer is the neural network architecture behind practically every modern LLM. It is built from a small set of parts — embeddings, positional information, attention, feed-forward layers, normalisation and residual connections — stacked many times. This lesson assembles them into a working (tiny, untrained) model.
Problem: attention ignores order
Attention compares tokens by content only. If you shuffle the input tokens, each token gets exactly the same output as before, just in a different row. "Dog bites man" and "man bites dog" would look identical:
import numpy as np
rng = np.random.default_rng(1)
X = rng.normal(size=(3, 4)) # embeddings for 3 tokens
def self_attention(X):
s = X @ X.T / np.sqrt(X.shape[1])
w = np.exp(s - s.max(axis=1, keepdims=True))
w /= w.sum(axis=1, keepdims=True)
return w @ X
out = self_attention(X)
perm = [2, 0, 1] # shuffle the tokens
out_shuffled = self_attention(X[perm])
print("same results, only reordered:", np.allclose(out[perm], out_shuffled))same results, only reordered: True
Solution: positional encodings
The fix is to add information about position to each token's embedding before the first layer. The original Transformer used fixed sinusoidal encodings: each dimension is a sine or cosine wave with a different frequency, so every position gets a unique pattern and nearby positions get similar patterns.
import numpy as np
import matplotlib.pyplot as plt
def positional_encoding(n_positions, d_model):
pos = np.arange(n_positions)[:, None]
i = np.arange(0, d_model, 2)[None, :]
angles = pos / (10000 ** (i / d_model))
pe = np.zeros((n_positions, d_model))
pe[:, 0::2] = np.sin(angles)
pe[:, 1::2] = np.cos(angles)
return pe
pe = positional_encoding(50, 32)
fig, ax = plt.subplots(figsize=(6, 3.5))
im = ax.imshow(pe, cmap="RdBu", aspect="auto")
ax.set_xlabel("embedding dimension"); ax.set_ylabel("position")
ax.set_title("Sinusoidal positional encodings")
fig.colorbar(im)
fig.tight_layout()
plt.show()
print("shape:", pe.shape)
print("position 0, first 4 dims:", np.round(pe[0, :4], 3))
print("position 1, first 4 dims:", np.round(pe[1, :4], 3))shape: (50, 32)
position 0, first 4 dims: [0. 1. 0. 1.]
position 1, first 4 dims: [0.841 0.54 0.533 0.846]
Low dimensions oscillate quickly and high dimensions slowly, a bit like the hands of a clock. Many modern LLMs use other schemes — learned position embeddings, or rotary position embeddings (RoPE), which rotate query and key vectors by an angle that depends on position — but the purpose is the same: tell attention where each token is.
One Transformer block
A block has two sub-layers, each wrapped in a residual connection (add the input back to the output) and layer normalisation (rescale each vector to a stable range):
x = x + Attention(LayerNorm(x)) # tokens exchange information
x = x + FeedForward(LayerNorm(x)) # each token is processed on its ownThe feed-forward network (also called the MLP) is two matrix multiplications with an activation in between, applied to every position independently. It is often described as where much of the model's stored knowledge lives, while attention moves information between positions.
import numpy as np
rng = np.random.default_rng(42)
n_tokens, d, d_ff = 5, 16, 64
def layer_norm(x, eps=1e-5):
mu = x.mean(axis=-1, keepdims=True)
var = x.var(axis=-1, keepdims=True)
return (x - mu) / np.sqrt(var + eps)
def causal_attention(x, Wq, Wk, Wv):
q, k, v = x @ Wq, x @ Wk, x @ Wv
s = q @ k.T / np.sqrt(d) + np.triu(np.full((len(x), len(x)), -np.inf), k=1)
w = np.exp(s - s.max(axis=1, keepdims=True))
return (w / w.sum(axis=1, keepdims=True)) @ v
def gelu(x):
return 0.5 * x * (1 + np.tanh(0.7978845608 * (x + 0.044715 * x ** 3)))
params = {name: rng.normal(0, 0.1, shape) for name, shape in
[("Wq", (d, d)), ("Wk", (d, d)), ("Wv", (d, d)), ("W1", (d, d_ff)), ("W2", (d_ff, d))]}
def block(x, p):
x = x + causal_attention(layer_norm(x), p["Wq"], p["Wk"], p["Wv"])
x = x + gelu(layer_norm(x) @ p["W1"]) @ p["W2"]
return x
x = rng.normal(size=(n_tokens, d))
for layer in range(3): # stack 3 blocks (sharing weights to keep it short)
x = block(x, params)
print(f"after block {layer + 1}: shape {x.shape}, mean |x| = {np.abs(x).mean():.3f}")
print("parameters per block:", sum(p.size for p in params.values()))after block 1: shape (5, 16), mean |x| = 0.864
after block 2: shape (5, 16), mean |x| = 0.947
after block 3: shape (5, 16), mean |x| = 1.079
parameters per block: 2816
The shape never changes: (tokens, d) in, (tokens, d) out. That is what makes it possible to stack dozens of blocks. (In a real model each block has its own weights; we reused one set to keep the code short.)
The full decoder-only model
token IDs ──► embedding + position ──► [block] × N ──► LayerNorm ──► linear to vocab ──► logitsGPT-style chat models are decoder-only Transformers: one stack with causal attention, trained to predict the next token. (The original 2017 Transformer had an encoder and a decoder for translation; encoder-only models such as BERT are used for classification and embeddings.)
How big does it get?
Most parameters sit in the attention and feed-forward matrices. A common rough estimate is about 12 × layers × d² for the blocks, plus vocab × d for the embedding table:
def approx_params(layers, d_model, vocab):
blocks = 12 * layers * d_model ** 2 # 4·d² attention + 8·d² feed-forward (d_ff = 4·d)
embeddings = vocab * d_model
return blocks + embeddings
configs = [("tiny demo", 3, 16, 100), ("small", 12, 768, 50_000), ("larger", 48, 4096, 100_000)]
for name, layers, d_model, vocab in configs:
print(f"{name:>9}: {approx_params(layers, d_model, vocab):>15,} parameters")tiny demo: 10,816 parameters
small: 123,334,656 parameters
larger: 10,073,276,416 parameters
These are illustrative configurations, not specific products; real architectures vary (grouped-query attention, mixture-of-experts layers and other variations change the count).
Go further: Building a Transformer Block writes the pre-norm block in NumPy and in PyTorch, and the next lesson trains a tiny character transformer with it.
Test yourself
Why do Transformers need positional information?
- Attention by itself treats the input as an unordered set of tokens
- To reduce the vocabulary size
- Positions are needed for tokenization
- To make the model smaller
What does a residual connection do?
- Removes the previous layer
- Adds a sub-layer's input to its output (x + f(x))
- Normalises the vocabulary
- Masks future tokens
GPT-style chat models are usually which kind of Transformer?
- Encoder-only
- Decoder-only with causal attention
- Convolutional
- Recurrent